class
Widget { };
class SpecialWidget: public Widget { };
void update(SpecialWidget * psw);
int main()
{
Widget * pw = new SpecialWidget;
update(dynamic_cast < SpecialWidget *> (pw));
// It seems to work.
}
class SpecialWidget: public Widget { };
void update(SpecialWidget * psw);
int main()
{
Widget * pw = new SpecialWidget;
update(dynamic_cast < SpecialWidget *> (pw));
// It seems to work.
}
When compiling, error message shows up as follows:
cannot dynamic_cast `pw' (of type `class Widget*') to type `class SpecialWidget*' (source type is not polymorphic)
why does it say source type is not polymorphic? Dose' t class SpecialWidget extends class Widget?
That's no doubt about that. So why?
Let us add some code to see:
class
Widget
{
public :
virtual void polymorphic( ) { } // add virtual method
};
class SpecialWidget
{
public :
virtual void polymorphic( ) { } // add virtual method
};
void update(SpecialWidget * psw);
int main( )
{
Widget * pw = new SpecialWidget;
update( dynamic_cast < SpecialWidget *> (pw) ); // Now it does work.
}
{
public :
virtual void polymorphic( ) { } // add virtual method
};
class SpecialWidget
{
public :
virtual void polymorphic( ) { } // add virtual method
};
void update(SpecialWidget * psw);
int main( )
{
Widget * pw = new SpecialWidget;
update( dynamic_cast < SpecialWidget *> (pw) ); // Now it does work.
}
Now, just adding some virtual funciton, no error message shows up.
So in C++ it seems polymorphic is not inheritance
, but virtual function.