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,
Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.
The actual reason is - a derived class has all information about a base class and also some extra bit of information. Now a pointer to a derived class will require more space and that is not sufficient in base class. So the a pointer to a derived class cannot point to it.
similarly a derived object is a base class object (as it's a sub class), so it can be pointed to by a base class pointer. However, a base class object is not a derived class object so it can't be assigned to a derived class pointer.
Using a qualified-id to call a base class' function works irrespectively of what happens to that function in the derived class - it can be hidden, it can be overridden, it can be made private (by using a using-declaration), you're directly accessing the base class' function when using a qualified-id.
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:
void someMethod(Base* bp) {
Derived *dp = dynamic_cast<Derived*>(bp);
if (dp != null)
dp->methodInDerivedClass();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With