void-pointer
void-pointer

Reputation: 14827

Inheritance of operator()

I am stumped by why the declaration of void operator()(int) in the base class in the code sample below is seemingly hidden when the derived class implements void operator()(int,int,int). How can I get the declaration of operator()(int) from the base class foo to be visible in the derived class bar? That is, how can I modify the example so that the invocation of operator()(int) works?

#include <iostream>

struct foo
{
        void operator()(int)
        {
                std::cout << "A" << std::endl;
        }
};

struct bar : foo
{
        // If this is uncommented, the code will not compile.
        // void operator()(int, int, int) {}
};

int main()
{
        bar b;
        b(1);
        return 0;
}

When compiled with g++ with the marked lines uncommented, the error message is along the lines of "no match for call to 'bar (int)' ... candidate is void bar::operator()(int,int,int) ... candidate expects 3 arguments, 1 provided."

Upvotes: 6

Views: 278

Answers (2)

huskerchad
huskerchad

Reputation: 1037

Note that operator() might make this look more confusing than it is. The classic example would probably be something more like bar::mymethod(int) and foo::mymethod(). The derived method hides the inherited method because of how resolution happens. The using declaration explained in another answer brings in foo's method for resolution.

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283674

That's right. Derived class functions hide base class functions rather than overloading. The fix is pretty simple though:

struct bar : foo
{
     using foo::operator();
     void operator()(int, int, int) {}
};

Upvotes: 6

Related Questions