Virtual Function Question
-
I'm actually using WTL in this project, but this appears to be a basic C++ question so I thought I'd ask it here. I have class A, which is a base class for class B. Class B is in turn a base class for class C. In class A there is a virtual function. Let's call it Func1(). This function is defined in both class A and C (the A version just asserts, the C version actually does the work). In class B there is a non-virtual function that calls Func1(). As I understand it, it should call the class C version of this function, but instead it's calling the class A version. Where have I gone wrong?
-
I'm actually using WTL in this project, but this appears to be a basic C++ question so I thought I'd ask it here. I have class A, which is a base class for class B. Class B is in turn a base class for class C. In class A there is a virtual function. Let's call it Func1(). This function is defined in both class A and C (the A version just asserts, the C version actually does the work). In class B there is a non-virtual function that calls Func1(). As I understand it, it should call the class C version of this function, but instead it's calling the class A version. Where have I gone wrong?
because class B is derived from class A. If you don't override Func1() in class B, Func1() from class A will be called because inherits Func1() from it's base class( class A ). Do not forget that class B is not related with class C. The relationship u described is from C to B and not from B to C.
-
I'm actually using WTL in this project, but this appears to be a basic C++ question so I thought I'd ask it here. I have class A, which is a base class for class B. Class B is in turn a base class for class C. In class A there is a virtual function. Let's call it Func1(). This function is defined in both class A and C (the A version just asserts, the C version actually does the work). In class B there is a non-virtual function that calls Func1(). As I understand it, it should call the class C version of this function, but instead it's calling the class A version. Where have I gone wrong?
Just FYI, this really does work, and is infact the basis of the template design pattern. Where I went wrong: class A was written by somebody else (in this case it was part of WTL written by Microsoft). I thought it was virtual, it wasn't. If it was virtual it would've worked, as I've now found out. Why it works: The method in class B that calls the virtual function is calling it on the this pointer. Thus, the virtual table is used to figure out which version to call, so even though class B doesn't know about class C, class C's definition of the function is used. Pretty cool when you do it right.