Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's assume there is such class hierarchy:

class A //base class

class B //interface

class C : public A, public B

Then C object is created:

A *object = new C();

Is it possible to cast object to B ?

Important: I assume I don't know that object is C. I just know that it implements interface B

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
271 views
Welcome To Ask or Share your Answers For Others

1 Answer

No. This is not possible (direct casting from A* to B*).

Because the address of A and B are at different locations in class C. So the cast will be always unsafe and possibly you might land up in unexpected behavior. Demo.

The casting should always go through class C. e.g.

A* pa = new C();
B* pb = static_cast<C*>(pa);
                   ^^^^ go through class C

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...