I want to call a derived class function that isn't defined in the base class using base class pointers. but this always raises the error:
error C2039: ‘derivedFunctionName’ : is not a member of ‘BaseClass’
Do you know how I could get around this?
Thanks,
You can call a derived class member through a pointer to a base class as long as the method is virtual. That's what polymorphism is about.
In order for that to work you must declare a virtual method (probably pure virtual) in the base class and overload it in the derived class.
Note that you will run into issues calling the derived member from the base method. Do some ARM or Meyers reading if this doesn't make sense to you.
You can't call a member that appears only in a derived class through a pointer to the base class; you have to cast it (probably using
dynamic_cast
) to a pointer to the derived type, first -- otherwise the compiler has no idea the method even exists.It might look something like this:
One way is to make the function
virtual
in the base class and then override it in the derived class. You don't have to define the function in the base class (although you can), but you can use the pure virtual syntax in the base classvirtual void foo() = 0;
if you don't want to provide an implementation in the base class.This will let you override it in the derived class and still call it in the base class through a base class pointer. This is known as 'polymorphism'.
You can also just cast it to a derived type at run time if you are sure it is actually a derived class pointer at that time. If it is not, it will crash.