Vortico
Vortico

Reputation: 2749

GCC deprecation message on override

In GCC, you can create a deprecation warning when someone calls a deprecated function with

void __attribute__((deprecated)) foo() {}

Can you create a similar deprecation warning when someone overrides a virtual method of a class?

Upvotes: 1

Views: 537

Answers (2)

Killzone Kid
Killzone Kid

Reputation: 6240

Using [[deprecated]] and [[deprecated(message)]] standard attributes (available since C++14) produce desired effect in Visual Studio both for usage of deprecated method and for attempt to override by issuing C4996 warning (which could be ignored). I cannot speak for other compilers, I expect since this is standard they should comply as well.

class Base
{
public:
    [[deprecated("dont use, deprecated")]] virtual void foo()
    {
    }
};

class Derived : public Base
{
public:
    void foo() override 
    {
    }
};


int main()
{
    Base b;
    b.foo();
}

This will produce 2 warnings, one for the override and one for the attempted use,

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249123

It will generate an error rather than a warning, but you could add the final specifier to the method declaration in your base class. Then no one could override it.

You could also generate a deprecation message at runtime (rather than compile time) by calling the function and seeing if it runs the base-class implementation or not (by setting a flag in the base-class implementation then checking it after the call).

Upvotes: 0

Related Questions