开发者

Does f(int) in base class inherited in derived derived class D which have f(double)? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why does an overridden function in the derived class hide other overloads of the base class?

Does f(int) in base class inherited in derived derived class D? if yes then why overloading is not working here. and if no then why f(int) is not inherited as class d is publicly derived. I am confused.

    class B {
    public:
        int f(int i) { cout << "f(int): "; return i+1; }
        // ...
    };

    class D : public B {
    public:
        double f(double d) { cout << "f(double): "; return d+1.3; }
        // .开发者_运维问答..
    };

    int main()
    {
        D* pd = new D;

        cout << pd->f(2) << '\n';
        cout << pd->f(2.3) << '\n';
    }


This is the Classical example for Function Hiding.
The overload resolution in C++ does not work across classes, A function in derived class Hides all the functions with identical name in the Base class. Compiler only sees the function in derived class for an derived class object.

You can Unhide all the base class functions for your derived class by using the using Declaration. in your derive class.

Adding,

using B::f;

in your derived class will enable your derived class object to access all the functions with the name f() int the Base class as if they were overloaded functions in Derived class.


This should be a good read:

What's the meaning of, Warning: Derived::f(char) hides Base::f(double)?


I think if you give a derived class a function with the same name as functions existing in a base class, the derived class' function will hide the base class' functions. If you merely wanted to overload, use the using keyword.

class B {
public:
    int f(int i) { cout << "f(int): "; return i+1; }
    // ...
};

class D : public B {
public:
    using B::f; //brings in all of B's "f" functions
                //making them equals of D's "f" functions.
    double f(double d) { cout << "f(double): "; return d+1.3; }
    // ...
};

int main()
{
    D* pd = new D;

    cout << pd->f(2) << '\n';
    cout << pd->f(2.3) << '\n';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜