Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...