quick question on polymorphism [modified]
-
Hi, Think I have got my hair in a mess, say I have a function that accepts a base class ptr, and I want to call a function on a class type that derives from the base class type. Is it possible to just do a dynamic / static cast on it? something like
void func(base* ptr) { //cast down hierachy so i can call my derived class function derived * derivedptr = dynamic_cast(ptr); //call my derived class function derivedptr->derivedfunction(); }
Thanks for any information.modified on Thursday, November 26, 2009 8:30 AM
-
Hi, Think I have got my hair in a mess, say I have a function that accepts a base class ptr, and I want to call a function on a class type that derives from the base class type. Is it possible to just do a dynamic / static cast on it? something like
void func(base* ptr) { //cast down hierachy so i can call my derived class function derived * derivedptr = dynamic_cast(ptr); //call my derived class function derivedptr->derivedfunction(); }
Thanks for any information.modified on Thursday, November 26, 2009 8:30 AM
The best way to do something like that is to declare the function as virtual in the base class and let the child class override this method. That's the basic principle of polymorphism.
Cédric Moonen Software developer
Charting control [v2.0] OpenGL game tutorial in C++ -
Hi, Think I have got my hair in a mess, say I have a function that accepts a base class ptr, and I want to call a function on a class type that derives from the base class type. Is it possible to just do a dynamic / static cast on it? something like
void func(base* ptr) { //cast down hierachy so i can call my derived class function derived * derivedptr = dynamic_cast(ptr); //call my derived class function derivedptr->derivedfunction(); }
Thanks for any information.modified on Thursday, November 26, 2009 8:30 AM
Like Cedric Moonen said, you should use virtual functions. But if you want to do what you're doing, you have to check the return of
dynamic_cast
for NULL.«_Superman_» I love work. It gives me something to do between weekends.
Microsoft MVP (Visual C++)