Sadeq
Sadeq

Reputation: 8043

Is it possible to recognize undesirable overriding of virtual functions?

For example:

struct A
{
    virtual void go() { };
};

struct B : public A
{
    void go() { };
};

Implicit overriding of function go can be undesirable, because it is not recognizable that B::go() is hiding or overriding the same function of struct A or even it may be a new function that does not exist in struct A. override feature of C++11 is useful when you want a desirable overriding of virtual functions, but in my case it is undesirable and i didn't want to override function go(), that means if i knew there was a virtual function I wouldn't override it in struct B.

What i want is something similar to [[check_names]] attribute proposal that didn't approve to C++11. Does C++ have a language feature for it?

By the way, do compilers (such as GCC and VC++) have an option to show a warning (a warning is enough if error is not available!) if an implicit overriding of a virtual function happens? if they have, can you provide an example for GCC?

EDIT: I am not talking about force or a language feature, all i want is a warning or anything that allow me to recognize the undesirable overriding.

EDIT: What can be a desirable overriding? it can be something like the following code:

struct A
{
    virtual void go() { };
};

struct B : public A
{
    virtual void go() { };
};

or:

struct A
{
    virtual void go() { };
};

struct B : public A
{
    void go() override { };
};

or something similar by using an attribute.

Upvotes: 3

Views: 126

Answers (1)

vsoftco
vsoftco

Reputation: 56577

I guess you can use tagging,

#include <iostream>
#include <memory>

using namespace std;

struct no_override_tag
{};

struct A
{
    virtual void go() { cout <<"A::go" << endl;};
};

struct B : public A
{
    void go(no_override_tag={}) { cout << "B::go" <<endl; };
};

int main()
{
    unique_ptr<A> upA(new B);
    upA->go(); // no override, calls `A::go()` instead of `B::go()`


}

Basically you add a default-initialized argument of a type no_override_tag as the last argument in B::go(), and this will make the signature of B::go different, no matter what you declaration you have in A. Not super elegant but it works, however I don't know why would you really want to do this.

Upvotes: 1

Related Questions