Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to mark a parent's virtual function final from a child class without reimplementing it

Tags:

c++

c++11

If I have the code:

struct Parent
{
    virtual void fn();
};

struct Child : public Parent
{
    virtual void fn() override final
    {
        Parent::fn();
    }
};

is there a way to have Parent::fn be final only when accessed through Child without re-implementing fn, so that some other class can override fn when deriving from Parent but not when deriving from Child?

like:

struct Child : public Parent
{
    virtual void fn() override final = Parent::fn;
};

or some other syntax?

like image 379
programmerjake Avatar asked Dec 24 '22 18:12

programmerjake


1 Answers

No, you can't do it without reimplementing it. So just reimplement it:

struct Child : public Parent
{
    virtual void fn() override final { Parent::fn(); }
};

N.B. saying virtual ... override final is entirely redundant, final is an error on a non-virtual function, so you should just say:

    void fn() final { Parent::fn(); }

See http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rh-override

like image 118
Jonathan Wakely Avatar answered Mar 01 '23 23:03

Jonathan Wakely