9

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?

1
  • I guess it is hiding because B::f and A:f are in different scope.
    – pic11
    Apr 12, 2011 at 13:58

4 Answers 4

9

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){ }
};
2
  • Why are you hiding it? Is it simply a rule or is there some reason for compiler to work like this?
    – gruszczy
    Apr 12, 2011 at 13:53
  • 2
    @gruszczy It’s a rule. It does make sense when the base class is later changed and introduces a new method of the same name as a derived class method. This in turn could lead to the new method being called in places in the client code where the old method was intended to be called. Essentially, this rule thus ensures backwards maintainability of code where base class interfaces are subject to being extended. Apr 12, 2011 at 13:57
4

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.

3

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){ }
};
2

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

Why?

Read this answer.

Solution

 using A::f; // add this above f's definition in the derived class

Not the answer you're looking for? Browse other questions tagged or ask your own question.