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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…