Calling subclass' method in inherited virtual function?

I am new to C++, but I was under the impression that virtual in C++ was the equivalent of abstract in Java. I have the following:

//A.h
class A {
public:
    void method();
protected:
    virtual void helper();
}

With the following cpp:

//A.cpp
#include "A.h"
void A::methodA() {
    //do stuff
    helper();
}

Then here's the derived class:

//B.h
#include "A.h"
class B: public A{
private:
    void helper2();
}

and the following derived cpp:

//B.cpp
#include "B.h"

void B::helper2() {
    //do some stuff
} 

void A::helper() {
    helper2();
}

However, the compiler does not seem to like that I am calling the helper2 method defined in the derived class, within a virtual method defined in the super class. It gives the error "error: 'helper2' was not declared in this scope". Is this not how I am supposed to use virtual methods?

Btw I can't use the keyword override .


[...] the compiler does not seem to like that I am calling the helper2 method defined in the derived class, within a virtual method defined in the super class. It gives the error "error: 'helper2' was not declared in this scope".

The error has nothing to do with the function being virtual. You can't call a derived class method from a base class. Methods declared in a derived simply don't exist in the base class.


Moreover, your assumption that virtual functions are the same as abstract functions is not true. They're not the same.

  • Virtual functions are functions that can be overridden by a derived class.

  • Abstract functions, aka pure virtual functions, are functions that need to be implemented by an inheriting class.

  • The confusing thing is that in Java, all non-static methods are virtual by default. In C++ you have to explicitly declare them virtual when needed.


    Also, you should be defining all member functions of A in either A.cpp or Ah , right now you're defining A::helper in B.cpp .

    链接地址: http://www.djcxy.com/p/38134.html

    上一篇: 使用抽象/虚拟的最佳实践

    下一篇: 在继承的虚函数中调用子类的方法?