A Single Pointer to the Parent class

Examine the example program named VIRTUAL5.CPP where we almost use a virtual method. Be just a little patient because we are almost ready to actually use a virtual method.

You will notice that this is another copy of our program with the keyword virtual omitted from line 8 and with a totally different main program. In this program, we only declare a single pointer to a class and the pointer is pointing to the base class of the class hierarchy. We will use the single pointer to refer to each of the four classes and observe what the output of the method named message() is.

A little digression is in order to understand how we can use a pointer which has been declared to point to one class, to actually refer to another class. If we referred to a vehicle (in the real world, not necessarily in this program), we could be referring to a car, a truck, a motorcycle, or any other kinds of transportation, because we are referring to a very general form of an object. If however, we were to refer to a car, we are excluding trucks, motorcycles, and all other kinds of transportation, because we are referring to a car specifically. The more general term of vehicle can therefore refer to many kinds of vehicles, but the more specific term of car can only refer to a single kind of vehicle, namely a car.

We can apply the same thought process in C++ and say that if we have a pointer to a vehicle (remembering that a pointer is actually a reference), we can use that pointer to refer to any of the more specific objects, and that is indeed legal in C++ according to the definition of the language. In a like manner, if we have a pointer to a car, we cannot use that pointer to reference any of the other classes including the vehicle class because the pointer to the car class is too specific and restricted to be used on any of the other classes.