Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A virtual function that must be overridden

Tags:

c++

Consider a base class class Base which has a function virtual void foo(void). This function is implemented in Base; i.e. is not pure virtual.

Is there a pattern I can use which when inheriting from this class, i.e. class Child : public Base, compels me to override foo?

like image 620
P45 Imminent Avatar asked Apr 29 '14 12:04

P45 Imminent


1 Answers

Other than making it a pure virtual function, there is no way to make the override required.

Note that the fact that a function is marked pure virtual does not mean that it cannot have an implementation in the base class - it means only that the derived class must override it.

struct Base {
    virtual void foo() = 0; // foo() is pure virtual
};
struct Derived : public Base {
    void foo() {            // Derived overrides the pure virtual
        cout << "Hello ";
        Base::foo();    // Call the implementation in the base
        cout << endl;
    }
};

void Base::foo() {
    cout << " world";
}

int main() {
    Derived d;
    d.foo();
    return 0;
}

This prints "Hello world", with the "world" part coming from the implementation in the base class.

Demo.

like image 178
Sergey Kalinichenko Avatar answered Oct 16 '22 10:10

Sergey Kalinichenko