Possible Duplicates:
C++ overload resolution
Why does an overridden function in the derived class hide other overloads of the base class?
Why the following example:
class A {
public:
void f(int x){ }
};
class B : public A {
public:
void f(float a, int b){ }
};
int main(){
B *b = new B;
b->f(1);
};
causes:
test.cpp: In function ‘int main()’: test.cpp:13: error: no matching function for call to ‘B::f(int)’ test.cpp:8: note: candidates are: void B::f(float, int)
f(int)
and f(float, int)
have different signatures. Why is it causing an error?
EDIT
I understand it's hiding. I am asking why is this happening?
Essentially, you are not overloading the base class method; by redefining method f
, you are hiding the base class method. You can prevent this by including it explicitly into the child class scope the following:
class B : public A {
public:
using A::f;
void f(float a, int b){ }
};
By declaring another function named 'f' in your class B, you are hiding the 'f' declared in A.
To get overloading to work along with inheritance, add a using directive to your class B.
class B : public A {
public:
using A::f;
void f(float a, int b){ }
};
This is because compiler looks in the scope of class B and finds only one method that it has to consider for overload resolution.
A::f is hidden by B:f. Use using
directive to overload base class method.
class B : public A {
public:
using A::f;
void f(float a, int b){ }
};
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