camino
camino

Reputation: 10594

how to force subclass to override a virtual function

sometimes I would like to force subclass to override a function, for example:

class A
{
    virtual void foo() = 0;
};

class B : public A
{
    virtual void foo() {...}
};

class C : public B
{
    //people may forget to override function foo
};

Upvotes: 5

Views: 2514

Answers (1)

R Sahu
R Sahu

Reputation: 206717

Declare the virtual function in the intermediate class also as a pure virtual function. Remember that you may provide an implementation of the function in the intermediate class even when it is declared to be pure virtual.

class A
{
    virtual void foo() = 0;
};

class B : public A
{
    virtual void foo() = 0;
};

void B::foo()
{
}

class C : public B
{
    // Now you must provide an implementation
    // if you want to create an instance of C.
};

This strategy works if you don't need to instantiate B. If you do need to instantiate B, a different strategy needs to be thought of. You also have to rethink your class hierarchy. All non-leaf classes should be abstract in a good design.

Thanks to @AustinMullins for providing a link to working code.

Upvotes: 7

Related Questions