In chapter 5, "Function and Operator Overloading," you saw how C++ enables you to override constructors, functions, and operators. It also lets you do the same thing between base and derived classes. You can override base class functions in derived classes. You do this when you want to enhance or change the way the base class function operates. Listing 6.4 demonstrates how to override base class functions in a derived class. Note The entire program for Listing 6.4 is on the CD in the folder \Source\Chapter06\Prog_06_04. It's in a file called Prog_06_04.cpp. Listing 6.4. Overriding the Print() function in the point2d class
Listing 6.4 gives a modified version of the program from Listing 6.1. It doesn't actually present the entire program. To save some space and focus on the discussion at hand, I've omitted all of the member functions you saw in Listing 6.1. The only member functions that appear in Listing 6.4 are two functions that are both named Print(). The point2d and point3d classes each contain their own version of Print(). The version of Print() in the point2d class prints the value in the private data member x, then prints a comma, and finally prints the value in the private data member y. The version of Print() in the point3d class begins on line 47. It calls the Print() function in the point2d class. The style of function call you see on line 49 is how functions in derived classes call the functions in base classes that they override. The call must specify the name of the base class, followed by the scope resolution operator, and then the name of the function. Note Functions in derived classes that override base class functions do not have to call the base class functions they override. They often do, but it is not required. As a result of calling the Print() function in the point2d class, the x and y values for the point are printed to the screen. After the Print() in the point3d class calls the Print() function in the point2d class, it prints a comma. It then prints the value in the private data member z. You can see on line 58 that the main() function calls the Print() function for the point3d class. Looking at just that one line of code, you cannot tell (nor should you care) that the Print() function in the point3d class invokes the Print() function in the point2d class. The fact that it gets its work done properly is all that counts. However, when you're writing the point3d class, it saves you time and effort to utilize the Print() function from the point2d class. Again, that's precisely the purpose of inheritance. |