Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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."

like image 536
void-pointer Avatar asked Dec 29 '11 16:12

void-pointer


People also ask

What is operator inheritance?

In C++, like other functions, assignment operator function is inherited in derived class. For example, in the following program, base class assignment operator function can be accessed using the derived class object. #include<iostream>

Is operator =() inherited?

Assignment operator is indeed not inherited. Inheriting that operator would enable you to assign a Base to a Derived , however Base b; p = a; will (rightfully) fail to compile.

Which operators are not inherited in C++?

It really is only constructors that aren't inherited, and I can't think of any other compiler-generated functions that could hide something from the parent as in operator= .

What is inheritance in C?

Inheritance is a mechanism of reusing and extending existing classes without modifying them, thus producing hierarchical relationships between them. Inheritance is almost like embedding an object into a class.


1 Answers

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) {}
};
like image 140
Ben Voigt Avatar answered Oct 13 '22 00:10

Ben Voigt