Hi,
If I static cast an object of a derived class to its base class, the object's virtual methods should be those of the base class. But this doesn't seem to be the case if I call such a virtual method via another method. The following is an extremely simplified version of my code. func3 in class B does not give "A: func1" as ouput, and I don't understand why:
#include <iostream>
using namespace std;
class A {
public:
virtual void func1() {cout << "A: func1" << endl;}
void func2() {func1();}
};
class B: public A {
public:
void func1() {cout << "B: func1" << endl;}
void func3() {static_cast<A*>(this)->func2();}
};
int main() {
B b;
b.func1();
b.func2();
// The following gives "B: func1" as output, not "A: func1"
b.func3();
}
One could do this to get "A: func1" as output:
void func4() {A::func1();}
but this doesn't solve my problem (let's assume I don't want to call func1 any way other than via func2). The only solution I can find that gives "A: func1" as output is:
void func5() {
A temp = *static_cast<A*>(this);
temp.func2();
}
but this is very slow and inefficient. Any suggestions? I have tried dynamic_cast and reinterpret_cast. Any explanation of why func 3 doesn't give "A: func1" as output would be particularly appreciated.
Thanks alot in advance for any help.