Search code examples
c++virtual

When is the "virtual" attribute actually needed in a derived class?


I'm trying to understand when/where exactly one should write the 'virtual' keyword in order for any descendant of a given class to enable polymorphic behavior, since I could not find specific informations about this question elsewhere.

For what I've tried, having virtual on a function in the base class automatically makes that function virtual for any descendants. However many snippets around the Internet often declare these functions again virtual in the descendants.

struct A {
    virtual void foo1() { std::cout << "[A] foo1.\n"; }
    virtual void foo2() { std::cout << "[A] foo2.\n"; }
};
struct B : public A {
    virtual void foo1() { std::cout << "[B] foo1.\n"; }
            void foo2() { std::cout << "[B] foo2.\n"; }
};

Compiling this code with g++ I get that both foo1 and foo2 have polymorphic behavior. In addition, even if I derive again from B and create a C class, and I implement foo2 again without the virtual keyword, foo2 still uses the v-table.

Is using the virtual keyword in derived classes only used for clarity and self-documentation, or is there some other effect that I'm not aware of?


Solution

  • For what I've tried, having virtual on a function in the base class automatically makes that function virtual for any descendants.

    This is true, the child automatically inherits the virtualness of the parent method.

    People restate virtual in child classes as a convention simply to explicitly show that the child intends to override a virtual method (we have override in C++11 though).