Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloaded method not seen in subclass [duplicate]

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?

like image 524
gruszczy Avatar asked Apr 12 '11 13:04

gruszczy


3 Answers

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){ }
};
like image 143
Konrad Rudolph Avatar answered Sep 19 '22 07:09

Konrad Rudolph


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.

like image 27
xDD Avatar answered Sep 21 '22 07:09

xDD


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){ }
};
like image 33
pic11 Avatar answered Sep 21 '22 07:09

pic11