You need the base function to be virtual.
Code:
class Base{
public:
virtual void foo(){cout<<"base foo"<<endl;}
};
But still, this shouldn't work the way you use it. You have a base class obj. If you cast it it magically turns to a derived class? Think this:
Code:
class Base{
public:
void foo(){cout<<"base foo"<<endl;}
};
class Derived: public Base{
public:
int a;
void foo(){cout<< a <<endl;}
Derived() {a = 1;}
};
void test(Derived* obj){
obj->foo();
}
int main(){
Base obj;
test((Derived*)&obj);
}
Now you understand that if you allocate a Base object it wont have the variable a. So how would it be able to call foo from the derived class?
You can go from Devired to Base, not the other way around!