Re: Dynamic Casting and Multiple Inheritance Query
"Ganga Sridhar" <gangasridhar@abosoftware.com> wrote in message
news:etu0vmY7IHA.4112@TK2MSFTNGP05.phx.gbl
Class A {}
Class X { void Open();}
Class B: public A, public X {}
Note - Open() function not defined in A, B.
Its defined only in X.
MyFunc()
{
A* pA = CreateB(){ return new B;}
I don't think this would compile. I assume it's pseudocode.
X* pX = dynamic_cast<X*>(pA);
pX->Open();
}
If you see the above function, pA is actually a pointer of class A
dynamic casted to pX class X which is not derived from A.
The only relationship is that pA is actually an object of class B
(which is multiple inherited from X).
Still however the above code compiles and executes successfully.
Yes. dynamic_cast uses runtime type information (RTTI) to know that pA
actually points to an instance of B, and from there it can find X.
Is such casting and calling of functions of an unrelated class safe?
Yes. It's not necessarily a good idea, but it's safe.
Is there any kind of problem expected?
Well, it's not going to work if you turn off RTTI (see /GR compiler
switch).
If the A* pointer doesn't actually point to B (or some other class
related to X) then dynamic_cast will return NULL. Be prepared for that.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925