C++ pure virtual methods

醉酒当歌 提交于 2019-12-05 10:08:50

The reason is, that the defined f (in Derived ) hides the f functions from the Base class. The solution is to add using. Like this:

class Derived : public Base
{
public:
    int f(int i)
    {
        return (10 + i);
    }

//  vvvvvvvvvvvvvv
    using Base::f;
};

The issue you're running into is orthogonal to pure virtual functions and has to do with how C++ does name resolution in class hierarchies.

When you write

obj.f();

C++ tries to look for a function named f so it knows what to call. Since obj is of type Derived, it starts inside of Derived and looks for a function called f. It ends up finding Derived::f(int), and even though this function takes an argument, C++ thinks this is the method you're trying to call and thus stops looking. The compiler then notices that you're trying to invoke it with no parameters, giving you the error about the function call.

To fix this, you need to tell the C++ compiler that it also needs to try looking for the function Base::f(), which is contained in the base class. To do this, you can change your definition of Derived as follows:

class Derived : public Base
{
public:
    int f(int i)
    {
        return (10 + i);
    }

    using Base::f;
};

This line using Base::f tells C++ that it should treat functions in Base named f as though they are part of Derived. That way, when the compiler tries looking up a function named f, it finds both Derived::f(int) and Base::f(). The call will then succeed because the compiler can figure out that you're trying to call Base::f() with the code that you've listed.

Hope this helps!

The definition of f(int) in the derived class hides the name of Base::f which you didn't override. All you need to do is to unhide this by writing using Base::f;in the derived class:

class Derived : public Base
{
public:

    using Base::f;   //note this line!

    int f(int i)
    {
        return (10 + i);
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!