Search code examples
c++inheritanceunresolved-externalpure-virtual

Inheritance, pure virtual functions and non-inline member function definitions


I have boiled down my issue to the following code all in a single *.cpp file:

class A {
public:
    A() {};

    int PerformAction() {
        return Action();
    }

protected:
    virtual int Action();
}

class B: public A {
protected:
    int Action();
}

int B::Action() {
   return 4;
}

int main() {
    B newB;
    newB.PerformAction();
};

The previous code throws an Unresolved external symbol error on B::Action(). Changing a::Action()'s definition to:

virtual int Action() = 0;

yields instead the Cannot instantiate abstract class compiler error where it is used in the main function. All of the answers I have seen relate to having the code spread across multiple files, but this is occurring all within one source file. I imagine it is related to B's implementation of Action() being outside the class definition of B but can't see any reason why it should cause any error.


Solution

  • Your error messages, taken together, indicate a signature mismatch between A::Action and B::Action, such that B::Action does not become an overrider. The signatures must match perfectly (including cv-qualification of this), except that return type covariance is allowed.

    And B::Action must be virtual. It will be implicitly if the signature matches, unless it is a template. Templates can't override.

    If you have a C++11 compiler, I suggest using the override keyword, to make signature mismatch a compile error.