Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ type casting for class and pointer

Tags:

c++

types

casting

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?

like image 760
Wei Shi Avatar asked Dec 09 '25 13:12

Wei Shi


1 Answers

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).

like image 136
Luchian Grigore Avatar answered Dec 12 '25 04:12

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!