I am trying to inherit two equally named methods with different parameter lists to a derived class. One of them is virtual and overridden in the derived class, the other one is non-virtual. Doing so, i get a compile error while trying to access the non-virtual method of the base class from an derived class object.
Here is the code snippet
class Base {
public:
void f() {
cout << "[Base::f()]" << endl;
}
virtual void f(int arg) {
cout << "[Base::f(" << arg << ")]" << endl;
}
};
class Deriv : public Base {
public:
virtual void f(int arg) {
cout << "[Deriv::f(" << arg << ")]" << endl;
}
};
int main() {
Deriv d;
d.f(-1);
d.f(); // <<-- compile error
return 0;
}
which produces the following compile error:
error: no matching function for call to ‘Deriv::f()’
note: candidates are: virtual void Deriv::f(int)
I am not an expert in C++, but until now I thought to be right in making the assumption that member methods can be completely distinguished by their signatures. Thus, the non-virtual method Base::f() should not be overridden and should remain accessible. Am I wrong with this?
Here are some interesting/additional comments on that:
So, since I already know how to avoid this compile error, I am mainly interested in why this error happens!
By default, methods are non-virtual, and they cannot be overridden. Virtual modifiers cannot be used with static, abstract, private, and override modifiers.
Base: Non-virtual display. because the Display method of the Base class is not a virtual method so the Derived class should not be able to override it.
You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method.
As a special case for virtual functions, the return types of the signatures may differ slightly (covariance). In overloading, function signatures with different argument types simultaneously act as candidates to be chosen when you make a function call.
In Deriv
, add this:
using Base::f;
In addition to the link given by @DumbCoder, you can find more details in my answer to a similar question: Overriding a Base's Overloaded Function in C++
Derived class function hides the base function defintion. Detailed explaination as to why and how
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