Insight 19.7.1.
Think of
virtual as meaning โa function we will wait to pick the best available version of at runtimeโ.
makeIntroduction(const Person& p). When it called p.introduce(), it will always use Person::introduce(), even if p is actually a Student. We would like makeIntroduction to always use the most appropriate version of introduce. If we pass it a Student, we would hope that it would call Student::introduce() instead of the Person version.
introduce()) result in many different behaviors.
virtual functions, the compiler generates code for the function call to examine the object at runtime in order to decide which function version to use.
virtual keyword before the functionโs declaration. Something like:
virtual void introduce() const { ... }
virtual in the derived classes just to clearly indicate that the function is virtual.
virtual keyword to the two versions of the introduce() functions Other than that, nothing has been changed. However, after that simple change, the makeIntroduction function now behaves in a polymorphic fashion. Try it out and pay attention the the version of .introduce() used for Alex.
virtual as meaning โa function we will wait to pick the best available version of at runtimeโ.
.getName() is not virtual as we donโt expect subclasses to want to provide a โbetterโ version of how to get the name of a Person. And the constructor canโt be made virtual - Student will never provide a better way to make a plain Person (it will provide a way to make a Student that happens to be a Person).
.getName() virtual. Try adding virtual before getName in Person. Nothing will happen other than the code will run an infinitesimal bit slower.
virtual to every function in a class that will be inherited. And if you donโt know if a class will be inherited from, assume it will be.
virtual?
virtual function must also use the virtual keyword on it.virtual.virtual function from its definition, you only add virtual to the declaration inside the class. The implementation outside can not have the virtual keyword.
class Person {
virtual void introduce() const; // In class declaration gets virtual
};
void Person::introduce() const {
// Outside of class definition of introduce does not get virtual
}
virtual to the definition the compiler will produce an error to let you know. You just need to know that the message error: โvirtualโ outside class declaration is trying to tell you that you made that mistake.
override keyword at the end of the declaration of a virtual function in a derived class:
class Student : public Person {
virtual void introduce() const override {...} // Example of using override
};
void intorduce() (spelling error!) in the child class and then wondering why it is never used. Doing so would make a new function in the child class instead of overriding a function from the parent class. With the override keyword, the compiler would mark inroduce() as an error because it does not successfully override any existing functions.