Wei Shi
Wei Shi

Reputation: 5055

C++ type casting for class and pointer

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?

Upvotes: 2

Views: 113

Answers (3)

user90843
user90843

Reputation:

object slicing, A acast=(A)b; slices B

Upvotes: 3

evanmcdonnal
evanmcdonnal

Reputation: 48086

The first example is an explicit cast the the compiler understand the object to be of type A. In the second example you're just setting the pointer and the compiler still sees the object as being type B.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258598

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

Upvotes: 7

Related Questions