Search code examples
c++inheritancevirtual

C++: Use virtual in every class in the inheritance hierarchy?


I have this code:

#include <iostream>

using namespace std;

class FooA {
    public:
    virtual void meth () {cout << "hiA\n";}
};
class FooB : public FooA{
    public:
    void meth () {cout << "hiB\n";}
};
class FooC : public FooB {
    public:
    void meth () {cout << "hiC\n";}
};

int main() {
    FooA a;
    a.meth();
    FooB b;
    b.meth();
    FooC c;
    c.meth();
    FooA* ptr = &a;
    ptr->meth();
    ptr = &b;
    ptr->meth();
    ptr = &c;
    ptr->meth();
    FooB* ptrB = &b;
    ptrB->meth();
    ptrB = &c;
    ptrB->meth();
}

The output is this:

hiA
hiB
hiC
hiA
hiB
hiC
hiB
hiC

The code is basic and self-explanatory. I tried different combinations of making meth() in each class virtual or not. This will change how the output, obviously, especially if FooA::meth() is not declared as virtual. I have come to the conclusion that it is probably best and most clear to just make every instance of that method virtual. Is there any reason not to?

Edit: I have another question. When you declare a class, and then define it outside of the class declaration, using ::

Like this

class Foo{
public:
virtual void bar();
};

void Foo::bar {
cout << "Hello";
}

Why can't I do something like

virtual void Foo::bar {
cout << "Hello";
}

Solution

  • Is there any reason not to?

    It's superfluous.

    If you have a method in a base class declared as virtual, this virtuality will be "inherited" by the overriding method.

    Other than that, maybe for documentation purposes it might be acceptable. However, remember that the best virtuals are private, employ the non-virtual interface idiom.

    With that done, the "for documentation" reason falls to the ground, since private methods need no public documentation.