Adding the keyword virtual

As you examine the next example program named VIRTUAL2.CPP, you will notice that there is one small change in line 8. The keyword virtual has been added to the declaration of the method named message() in the parent class.

It may be a bit of a disappointment to you to learn that this program operates no differently than the last example program. This is because we are using objects directly and virtual methods

have nothing to do with objects, only with pointers to objects as we will see soon. There is an additional comment in line 46 illustrating that since all four objects are of different classes, it is impossible to assign any object to any other object in this program. We will soon see that some pointer assignments are permitted between objects.

After you are sure that the fact that they are virtual functions, or methods, has nothing to do with the objects as they are instantiated, compile and execute this example program to see if your compiler results in the same output as that listed.

Using Object Pointers

Examine the example program named VIRTUAL3.CPP and you will find a repeat of the first program but with a different main program.

In this program the keyword virtual has been removed from the method declaration in the parent class in line 8, and the main program declares pointers to the objects rather than declaring the objects themselves in lines 37 through 40. Since we only declared pointers to the objects we find it necessary to allocate the objects before using them by using the new operator in lines 42 through 49. Upon running the program, we find that even though we are using pointers to the objects we have done nothing different than what we did in the first program. Upon execution, we find that the program operates in exactly the same manner as the first example program in this chapter. This should not be surprising because a pointer to a method can be used to operate on an object in the same manner as an object can be manipulated.

Be sure to compile and execute this program before continuing on to the next example program. The observant student will notice that we failed to deallocate the objects prior to terminating the program. As always, in such a simple program, it doesn’t matter because the heap will be cleaned up automatically when we return to the operating system.