Calling child class methods from parent class pointers
-
What I am trying to do is create a base class that provides a basic interface and several child classes that implement the interface and extend it a little bit. I would then like to create a child class (at run time using pointers to the base class) whose type is determined by data in a table. So far so good. In the code which has the pointer I am trying to call some of the functions that extend the interface depending on the situation. Compiler chokes (rightly) telling me the virtual base class doesn't implement those functions. I can get around this by making the virtual base class define all the possible functions in the child classes and put dummy implementations in some child classes but it seems in-elegant. Is there a better way to do this?
-
What I am trying to do is create a base class that provides a basic interface and several child classes that implement the interface and extend it a little bit. I would then like to create a child class (at run time using pointers to the base class) whose type is determined by data in a table. So far so good. In the code which has the pointer I am trying to call some of the functions that extend the interface depending on the situation. Compiler chokes (rightly) telling me the virtual base class doesn't implement those functions. I can get around this by making the virtual base class define all the possible functions in the child classes and put dummy implementations in some child classes but it seems in-elegant. Is there a better way to do this?
Since you are using the base class pointer to call the functions, those functions must exist as virtual or pure virtual in the base class. In the derived classes, you must override whatever virtual functions are needed. In the case of pure virtual functions, it is mandatory that you implement this in the derived classes. So instead of having dummy implementations is several derived classes, have a dummy implementation in the base class and don't make it pure virtual.
«_Superman_» I love work. It gives me something to do between weekends.
-
Since you are using the base class pointer to call the functions, those functions must exist as virtual or pure virtual in the base class. In the derived classes, you must override whatever virtual functions are needed. In the case of pure virtual functions, it is mandatory that you implement this in the derived classes. So instead of having dummy implementations is several derived classes, have a dummy implementation in the base class and don't make it pure virtual.
«_Superman_» I love work. It gives me something to do between weekends.
I did it by adding the virtual functions to the base class. Just seems like a clunky solution. Thx very much.