DUPLICATED METHOD NAMES

You will notice that both of the parent classes have a method named initialize(), and both of these are inherited into the subclass with no difficulty. However, if we attempt to send a message to one of these methods, we will have a problem, because the system does not know which we are referring to. This problem will be solved and illustrated in the next example program.

Before going on to the next example program, it should be noted that we have not declared any objects of the two parent classes in the main program. Since the two parent classes are simply normal classes themselves, it should be apparent that there is nothing magic about them and they can be used to define and manipulate objects in the usual fashion. You may wish to do this to review your knowledge of simple classes and objects of those classes.

Be sure to compile and execute this program after you understand its operation completely.

MORE DUPLICATE METHOD NAMES

The second example program in this chapter named MULTINH2.CPP, illustrates the use of classes with duplicate method names being inherited into a derived class.

If you study the code, you will find that a new method has been added to all three of the classes named cost_per_full_day(). This was done intentionally to illustrate how the same method name can be used in all three classes. The class definitions are no problem at all, the methods are simply named and defined as shown. The problem comes when we wish to use one of the methods since they are all the same name and they have the same numbers and types of parameters and identical return types. This prevents some sort of an overloading rule to disambiguate the message sent to one or more of the methods.

The method used to disambiguate the method calls are illustrated in lines 60, 64, and 68 of the main program. The solution is to prepend the class name to the method name with the double colon as used in the method implementation definition. This is referred to as qualifying the method name. Qualification is not necessary in line 68 since it is the method in the derived class and it will take precedence over the other method names. Actually, you could qualify all method calls, but if the names are unique, the compiler can do it for you and make your code easier to write and read.

Be sure to compile and execute this program and study the results. The observant student will notice that there is a slight discrepancy in the results given in lines 79 through 81, since the first two values do not add up to the third value exactly. This is due to the limited precision of the float variable but should cause no real problem.

Share
Tweet
Share
Pin