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."
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>
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.
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= .
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.
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) {}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With