Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding overloaded virtual function

Consider the following hierarchy of structs:

struct I1 {
    virtual void doit() = 0;
};

struct I2 {
    virtual void doit(int) = 0;
};

struct I12 : I1, I2 {
    using I1::doit;
    using I2::doit;
};

struct Derived : I12 {
    void doit(int) override {}
};

Compiling this (using clang, or g++ with -Woverloaded-virtual) gives me a warning:

'Derived::doit' hides overloaded virtual function [-Woverloaded-virtual]

However, if I change I12 to the following, it compiles fine under clang, while g++ -Woverloaded-virtual still gives a warning:

struct I12 : I1, I2 {
    using I1::doit;
    void doit(int) override = 0;
};

Where is the difference between using I2::doit and void doit(int) override = 0? Naively, I would have thought that the former is sufficient to inform the compiler that I am aware that there are two versions of doit.

like image 635
phimuemue Avatar asked Oct 04 '16 11:10

phimuemue


People also ask

Can virtual functions be overloaded?

It is not possible for these functions to get overloaded.

Can we make virtual function private?

A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class.

Can we override private virtual function?

A private virtual function can be overridden by derived classes, but can only be called from within the base class. This is actually a useful construct when you want that effect.

Do virtual functions need to be overriden?

¶ Δ A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be “pure” using the curious =0 syntax.


1 Answers

It complains that doit is hidden in Derived. A fix:

struct Derived : I12 {
    using I12::doit; // Bring all doit declarations from I12 into this scope.
    void doit(int) override {}
};
like image 51
Maxim Egorushkin Avatar answered Oct 17 '22 08:10

Maxim Egorushkin