What Is virtual?

Lines 26 and 27 of Listing 22.4 show both functions qualified with the keyword virtual. This is important when functions are to be overridden, because it is the only way to make sure that class polymorphism works properly.

When a function outside an object calls a function in the object, the compiler generates code to perform the function call. If a function does not have the virtual keyword, the compiler assumes that the caller will want to call the function as implemented in the class the caller has at hand. Unfortunately, if the caller has a reference to a superclass of the class actually used to instantiate the object, and the derived class has overridden the function being called, the caller will not use the derived class's ...

Get SAMS Teach Yourself C++ in 10 Minutes SECOND EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.