Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to emit a warning if an overriding method don't call the overridden implementation in C++?

Is there a function attribute (standard or compiler extension) that emits a warning if an overriding method doesn’t call the overridden method?

Like this:

class A
{
protected:
    [[please_call]]
    virtual void foo() { /* ... */ };
};

class B : public A
{
protected:
    void foo() override {}
    // WARNING: B::foo() does not call A::foo()
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way to do this is to use another function in the base class and the call the virtual function in that function. That would look like

class Base
{
public:
    void doFoo() { Base::doFooImpl(); doFooImpl(); }
private:
    virtual void doFooImpl() { std::cout << "Base\n"; }
};

class Derived : public Base
{
private:
    void doFooImpl() override { std::cout << "Dervied\n"; }
};

int main()
{
    Derived d;
    d.doFoo();
}

output:

Base
Derived

Live example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading