Unable to call derived class function using base c

2020-06-22 08:48发布

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,

标签: c++
3条回答
Summer. ? 凉城
2楼-- · 2020-06-22 09:12

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.

查看更多
Deceive 欺骗
3楼-- · 2020-06-22 09:20

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();
}
查看更多
成全新的幸福
4楼-- · 2020-06-22 09:29

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.

查看更多
登录 后发表回答