5
votes

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,

3
Can you show us the related code?Borgleader
That's a bad design, no less.Bartek Banachewicz
class Material { public: void foo() { cout << "Class Material"; } }; class Unusual_Material : public Material { public: void fooo() { cout << "Class Unusual_Material"; } }; int main() { Material strange = Unusual_Material(); strange.foo0(); return 0; }Sujeeth Damodharan
Maybe I am a little late, but @BartekBanachewicz would you mind explaining why it is bad design?Tu.Ma.
@Tu.ma Because a code written in terms of the base class should have no expectations on the derived type being used. Either the function should be present on the base, or the derived type should be used instead.Bartek Banachewicz

3 Answers

14
votes

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();
}
5
votes

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 class virtual 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.

2
votes

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.