method in the derived class got executed without a *virtual* keyword in the referred class

江枫思渺然 提交于 2019-12-02 21:22:34

问题


class vehicle
{
public:
    virtual void drive()
    {
        cout<<"in vehicle drive"<<endl;
    }
};
class bus:public vehicle
{
public:
    void drive()
    {
        cout<<"in bus drive"<<endl;
    }
};
class supervehicle:public bus
{
public:
    void drive()
    {
        cout<<"in supervehicle"<<endl;
    }
};


int main()
{
    bus *b;
    b=new supervehicle();
    b->drive();
    return 0;
}

I expected the ouput as "in bus drive", but the output is "in supervehicle". If the virtual keyword is associated with the drive method in the bus class then for sure the output should be in bus drive. I know that we have inherited the vehicle class, but still we have created the pointer for bus class only. Could somebody please help me why the virtual keyword in the vehicle class is affecting the bus class's method and where am I missing the point?


回答1:


The virtual keyword is a specifier that signifies the function should be called via dynamic dispatch. It doesn't require repeating in each derived class; once a member function is virtual, it is virtual in each derived class.

And the one called via dynamic dispatch is the version from the most derived class that overrides it. So in your case, the dynamic type of the object pointed to by b is supervehicle, so the function called is supervehicle::drive, and not bus::drive.

A related specifier, that came in the 2011 revision of the C++ standard is override. You should use it on overridden functions to let the compiler know you are attempting to override a virtual function. If you made a mistake in the functions prototype, the compiler will issue a diagnostic.



来源:https://stackoverflow.com/questions/42083237/method-in-the-derived-class-got-executed-without-a-virtual-keyword-in-the-refe

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