Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inheritance casting from base class to different derived class

Tags:

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

like image 509
Andrew Avatar asked Sep 15 '11 05:09

Andrew


People also ask

What is meant by multiple inheritance deriving a base class from derived class?

You can derive a class from any number of base classes. Deriving a class from more than one direct base class is called multiple inheritance. In the following example, classes A , B , and C are direct base classes for the derived class X : class A { /* ... */ }; class B { /* ... */ }; class C { /* ...

Can be inherited by a derived class from a base class?

The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive.

Can a class serve as a base class for multiple derived classes?

When a class serves as base class for many derived classes, the situation is called: polymorphism.

Does members can be accessed in derived class in multiple inheritance?

Which members can't be accessed in derived class in multiple inheritance? Explanation: The private member's are available for only the class containing those members. Derived classes will have access to protected and public members only.


2 Answers

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

like image 56
iammilind Avatar answered Oct 11 '22 19:10

iammilind


The way to go from any type to any other is dynamic_cast. But it requires the object to be polymorphic. In general this requires a v-table to be associated to both A and B, so: if A and B have at least one virtual function, and RTTI is not disable,

A* pa1 = new C; A* pa2 = new A;  B* pb1 = dynamic_cast<B*>(pa1); B* pb2 = dynamic_cast<B*>(pa2); 

will result in pb2 to be null, and pb1 to point to the B part of the object containing *pa1 as its A part. (The fact it's C or whatever other derived from those two bases doesn't matter).

Otherwise, where all needs to be static, you have to go through C

B* pb = static_cast<B*>(static_cast<C*>(pa)); 

Note that static_cast<B*>(pA) cannot compile, being A and B each other unrelated.

like image 37
Emilio Garavaglia Avatar answered Oct 11 '22 19:10

Emilio Garavaglia