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
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 { /* ...
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.
When a class serves as base class for many derived classes, the situation is called: polymorphism.
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.
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
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.
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