class A{
public:
virtual void foo() {cout << "A::foo" << endl;}
};
class B: public A{
public:
virtual void foo() {cout << "B::foo" << endl;}
};
int main(void){
A a;
B b;
A acast=(A)B;
A *apointer=&B;
acast.foo(); // A::foo
apointer->foo() //B::foo
return 0;
}
Why does the two prints behave differently?
A acast=(A)b;(assuming this is what you actually have) slices the object and uses the sliced object to copy-construct anA. It’s equivalent toA acast=A(b);.acastis of dynamic and static typeA– no longer aB. It’s a completely new object.A *apointer=&b;, by contrast, is a pointer to an object whose dynamic type isB. The originalbobject isn’t modified, it’s just referred to by a pointer to the base type. Since the dynamic type isB, the methodfoofromBis called (because it’svirtualand that’s how polymorphism works).