Overloaded method not seen in subclass

Possible duplicates:
C ++ Overload Resolution
Why does an overridden function in a 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 the function 'int main (): test.cpp: 13: error: there is no corresponding function to call in' B :: f (int) test.cpp: 8: note: candidates: void B :: f ( float, int)

f(int) and f(float, int) have different signatures. Why does this cause an error?

EDIT

I understand that this is hidden. I ask why this is happening?

+6
source share
4 answers

Essentially, you do not overload the base class method; With the redefining f method, you hide the base class method. You can prevent this by including it explicitly in the scope of the child class as follows:

 class B : public A { public: using A::f; void f(float a, int b){ } }; 
+6
source

By declaring another function named "f" in your class B, you hide the "f" declared in A.

To overload work with inheritance, add a usage directive to your class B.

 class B : public A { public: using A::f; void f(float a, int b){ } }; 

This is because the compiler scans the scope of class B and finds only one method that it should consider when resolving overloads.

+3
source

A :: f is hidden B: f. Use the using directive to overload the base class method.

 class B : public A { public: using A::f; void f(float a, int b){ } }; 
+2
source

void f(float a, int b){ } , defined in the derived class, hides void f(int x){ } in the base class.

Why?

Read this answer.

Decision

  using A::f; // add this above f definition in the derived class 
+1
source

Source: https://habr.com/ru/post/885732/


All Articles