Re: Fix Virtual Base Class Pointer
Immortal Nephi <Immortal_Nephi@hotmail.com> wrote:
CommandMain derived class is derived from Command1, Command2, and
Command3 derived classes. Command1, Command2, and Command3 derived
classes are derived from robot virtual base class.
I try to assign Robot Pointer to CommandMain. Then Run() function is
always invoked inside CommandMain derived class. How can you use
dynamic_cast? Dynamic_cast should be enabled to invoke Run() inside
either Command1, Command2, or Command3 derived classes.
Please advise?
First, to answer your question directly, you need to dynamic_cast just
as you suspected:
void foo(Robot* aRobot)
{
CommandMain* aCommandMain = dynamic_cast<CommandMain*>(aRobot);
aCommandMain->Command1::Run();
aCommandMain->Command2::Run();
aCommandMain->Command3::Run();
}
I have to say though I think that this is extremely bad form. If you
have to do something like this, then your design is probably using
inheritance too extensively and inappropriately.