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 an A. It's equivalent to A acast=A(b);. acast is of dynamic and static type A - no longer a B. It's a completely new object.
A *apointer=&b;, by contrast, is a pointer to an object whose dynamic type is B. The original b object isn't modified, it's just referred to by a pointer to the base type. Since the dynamic type is B, the method foo from B is called (because it's virtual and that's how polymorphism works).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With