home *** CD-ROM | disk | FTP | other *** search
/ Power Programmierung 2 / Power-Programmierung CD 2 (Tewi)(1994).iso / c / tutorial / cpptutor / text / chap09.txt < prev    next >
Encoding:
Text File  |  1994-05-15  |  22.9 KB  |  522 lines

  1.  
  2.  
  3.  
  4.                                                         Chapter 9
  5.                        MULTIPLE INHERITANCE AND FUTURE DIRECTIONS
  6.  
  7. Multiple inheritance is the ability to inherit data and methods 
  8. from more than one class into a subclass.  Multiple inheritance 
  9. and a few of the other recent additions to the language will be 
  10. discussed in this chapter along with some of the expected future 
  11. directions of the language.
  12.  
  13. Several companies have C++ compilers available in the 
  14. marketplace, and others are sure to follow.  Because the example 
  15. programs in this tutorial are designed to be as generic as 
  16. possible, most should be compilable with any good quality C++ 
  17. compiler provided it follows the AT&T definition of version 2.1 
  18. or newer.  Many of these examples will not work with earlier 
  19. definitions because the language was significantly changed with 
  20. the version 2.1 update.
  21.  
  22. After completing this tutorial, you should have enough experience 
  23. with the language to study additional new constructs on your own 
  24. as they are implemented by the various compiler writers.  We will 
  25. update the entire tutorial as soon as practical following 
  26. procurement of any new compiler, but hopefully the language will 
  27. not change rapidly enough now to warrant an update oftener than 
  28. annually.  Please feel free to contact us for information on 
  29. updates to the Coronado Enterprises C++ tutorial.
  30.  
  31.  
  32. MULTIPLE INHERITANCE
  33. -----------------------------------------------------------------
  34. A major recent addition to the C++ language is the ability to 
  35. inherit methods and variables from two or more parent classes 
  36. when building a new class.  This is called multiple inheritance, 
  37. and is purported by many people to be a major requirement for an 
  38. object oriented programming language.  Some writers, however, 
  39. have expressed doubts as to the utility of multiple inheritance.  
  40. To illustrate the validity of this, it was not easy to think up a 
  41. good example of the use of multiple inheritance as an 
  42. illustration for this chapter.  In fact, the resulting example is 
  43. sort of a forced example that really does nothing useful.  It 
  44. does however, illustrate the mechanics of the use of multiple 
  45. inheritance with C++, and that is our primary concern at this 
  46. time.  
  47.  
  48. The biggest problem with multiple inheritance involves the 
  49. inheritance of variables or methods from two or more parent 
  50. classes with the same name.  Which variable or method should be 
  51. chosen as the inherited variable or method if two or more have 
  52. the same name?  This will be illustrated in the next few example 
  53. programs.
  54.  
  55.  
  56.  
  57.                                                          Page 9-1
  58.  
  59.            Chapter 9 - Multiple Inheritance and Future Directions
  60.  
  61. SIMPLE MULTIPLE INHERITANCE
  62. -----------------------------------------------------------------
  63. An examination of the file named MULTINH1.CPP  ==================
  64. will reveal the definition of two very simple     MULTINH1.CPP
  65. classes in lines 4 through 27 named            ==================
  66. moving_van and driver.  In order to keep the 
  67. program as simple as possible, all of the member methods are 
  68. defined as inline functions.  This puts the code for the methods 
  69. where it is easy to find and study.  You will also notice that 
  70. all variables in both classes are declared to be protected so 
  71. they will be readily available for use in any class which 
  72. inherits them.  The code for each class is kept very simple so 
  73. that we can concentrate on studying the interface to the methods 
  74. rather than spending time trying to understand complex methods.  
  75. As mentioned previously, chapter 12 will illustrate the use of 
  76. non-trivial methods.
  77.  
  78. In line 30, we define another class named driven_truck which 
  79. inherits all of the data and all of the methods from both of the 
  80. previously defined classes.  In the last two chapters, we studied 
  81. how to inherit a single class into another class, and to inherit 
  82. two or more classes, the same technique is used except that we 
  83. use a list of inherited classes separated by commas as 
  84. illustrated in line 30.  The observant student will notice that 
  85. we use the keyword public prior to the name of each inherited 
  86. class in order to be able to freely use the methods within the 
  87. subclass.  In this case, we didn't define any new variables, but 
  88. we did introduce two new methods into the subclass in lines 32 
  89. through 39.
  90.  
  91. We declared an object named chuck_ford which presumably refers to 
  92. someone named Chuck who is driving a Ford moving van.  The object 
  93. named chuck_ford is composed of four variables, three from the 
  94. moving_van class, and one from the driver class.  Any of these 
  95. four variables can be manipulated in any of the methods defined 
  96. within the driven_truck class in the same way as in a singly 
  97. inherited situation.  A few examples are given in lines 47 
  98. through 56 of the main program and the diligent student should be 
  99. able to add additional output messages to this program if he 
  100. understands the principles involved.
  101.  
  102. All of the rules for private or protected variables and public or 
  103. private method inheritance as used with single inheritance 
  104. extends to multiple inheritance.
  105.  
  106.  
  107. DUPLICATED METHOD NAMES
  108. -----------------------------------------------------------------
  109. You will notice that both of the parent classes have a method 
  110. named initialize(), and both of these are inherited into the 
  111. subclass with no difficulty.  However, if we attempt to send a 
  112. message to one of these methods, we will have a problem, because 
  113.  
  114.  
  115.                                                          Page 9-2
  116.  
  117.            Chapter 9 - Multiple Inheritance and Future Directions
  118.  
  119. the system does not know which we are referring to.  This problem 
  120. will be solved and illustrated in the next example program.
  121.  
  122. Before going on to the next example program, it should be noted 
  123. that we have not declared any objects of the two parent classes 
  124. in the main program.  Since the two parent classes are simply 
  125. normal classes themselves, it should be apparent that there is 
  126. nothing magic about them and they can be used to define and 
  127. manipulate objects in the usual fashion.  You may wish to do this 
  128. to review your knowledge of simple classes and objects of those 
  129. classes.
  130.  
  131. Be sure to compile and execute this program after you understand 
  132. its operation completely.
  133.  
  134.  
  135. MORE DUPLICATE METHOD NAMES
  136. -----------------------------------------------------------------
  137. The second example program in this chapter     ==================
  138. named MULTINH2.CPP, illustrates the use of        MULTINH2.CPP
  139. classes with duplicate method names being      ==================
  140. inherited into a derived class.  If you 
  141. study the code, you will find that a new method has been added to 
  142. all three of the classes named cost_per_full_day().  This was 
  143. done intentionally to illustrate how the same method name can be 
  144. used in all three classes.  The class definitions are no problem 
  145. at all, the methods are simply named and defined as shown.  The 
  146. problem comes when we wish to use one of the methods since they 
  147. are all the same name and they have the same numbers and types of 
  148. parameters and identical return types.  This prevents some sort 
  149. of an overloading rule to disambiguate the message sent to one or 
  150. more of the methods.
  151.  
  152. The method used to disambiguate the method calls are illustrated 
  153. in lines 60, 64, and 68 of the main program.  The solution is to 
  154. prepend the class name to the method name with the double colon 
  155. as used in the method implementation definition.  This is 
  156. referred to as qualifying the method name.  Qualification is not 
  157. necessary in line 68 since it is the method in the derived class 
  158. and it will take precedence over the other method names.  
  159. Actually, you could qualify all method calls, but if the names 
  160. are unique, the compiler can do it for you and make your code 
  161. easier to write and read.
  162.  
  163. Be sure to compile and execute this program and study the 
  164. results.  The observant student will notice that there is a slight 
  165. discrepancy in the results given in lines 79 through 81, since the 
  166. first two values do not add up to the third value exactly.  This 
  167. is due to the limited precision of the float variable but should 
  168. cause no real problem.
  169.  
  170.  
  171.  
  172.  
  173.                                                          Page 9-3
  174.  
  175.            Chapter 9 - Multiple Inheritance and Future Directions
  176.  
  177. DUPLICATED VARIABLE NAMES
  178. -----------------------------------------------------------------
  179. If you will examine the example program named  ==================
  180. MULTINH3.CPP, you will notice that each base      MULTINH3.CPP
  181. class has a variable with the same name.       ==================
  182.  
  183. According to the rules of inheritance, an object of the 
  184. driven_truck class will have two variables with the same name, 
  185. weight.  This would be a problem if it weren't for the fact that 
  186. C++ has defined a method of accessing each one in a well defined 
  187. way.  You have probably guessed that we will use qualification to 
  188. access each variable.  Lines 38 and 45 illustrate the use of the 
  189. variables.  It may be obvious, but it should be explicitly 
  190. stated, that there is no reason that the subclass itself cannot 
  191. have a variable of the same name as those inherited from the 
  192. parent classes.  In order to access it, no qualification would 
  193. be required.
  194.  
  195. It should be apparent to you that once you understand single 
  196. inheritance, multiple inheritance is nothing more than an 
  197. extension of the same rules.  Of course, if you inherit two 
  198. methods or variables of the same name, you must use qualification 
  199. to allow the compiler to select the correct one.  
  200.  
  201. Constructors are called for both classes before the derived class 
  202. constructor is executed.  The constructors for the base classes 
  203. are called in the order they are declared in the class header 
  204. line.
  205.  
  206.  
  207. PRACTICAL MULTIPLE INHERITANCE
  208. -----------------------------------------------------------------
  209. Examine the example program named DATETIME.H   ==================
  210. for a practical example using multiple             DATETIME.H
  211. inheritance.  You will notice that we are      ==================
  212. returning to our familiar new_date and 
  213. time_of_day classes from earlier chapters.
  214.  
  215. There is a good deal to be learned from this very short header 
  216. file since it is our first example of member initialization.  
  217. There are two constructors for this class, the first being a very 
  218. simple constructor that does nothing in itself, as is evident 
  219. from an examination of line 12.  This constructor allows the 
  220. constructors to be executed for the classes new_date and 
  221. time_of_day.  In both cases a constructor will be executed that 
  222. requires no parameters, and such a constructor is available for 
  223. each of these two classes.
  224.  
  225. The second constructor is more interesting since it does not 
  226. simply use the default constructor, but instead passes some of 
  227. the input parameters to the inherited class constructors.  
  228. Following the colon in line 13 are two member initializers which 
  229. are used to initialize members of this class.  Since the two 
  230.  
  231.                                                          Page 9-4
  232.  
  233.            Chapter 9 - Multiple Inheritance and Future Directions
  234.  
  235. parent classes are inherited, they are also members of this class 
  236. and can be initialized as shown.  Each of the member initializers 
  237. is actually a call to a constructor of the parent classes and it 
  238. should be evident that there must be a constructor with the 
  239. proper number of input parameters to respond to the messages 
  240. given.  You will note that in line 14, we are actually calling 
  241. the constructor with no parameters given explicitly.  If we 
  242. chose, we could simply let the system call that constructor 
  243. automatically, but this gives us an explicit comment on what is 
  244. happening.
  245.  
  246.  
  247. MORE ABOUT MEMBER INITIALIZERS
  248. -----------------------------------------------------------------
  249. Actually, we can use the member initializer to initialize class 
  250. members also.  If we had a class member of type int named 
  251. member_var, we could initialize it also by mentioning the name of 
  252. the member followed by the value we desired to initialize it to 
  253. in parentheses.  If we wished to initialize it to the value 13, 
  254. we could use the following line of code in the member initializer 
  255. list;
  256.  
  257.    member_var(13),
  258.  
  259. Following all member initialization, the normal constructor code 
  260. for the derived class is executed which in this case is given in 
  261. line 16.
  262.  
  263.  
  264. ORDER OF MEMBER INITIALIZATION
  265. -----------------------------------------------------------------
  266. The order of member initialization may seem a bit strange, but it 
  267. does follow a few simple rules.  The order of member 
  268. initialization does not follow the order given by the 
  269. initialization list, but another very strict order over which you 
  270. have complete control.  All inherited classes are initialized 
  271. first in the order they are listed in the class header.  If lines 
  272. 14 and 15 were reversed, class new_date would still be 
  273. initialized first because it is mentioned first in line 8.  It 
  274. has been mentioned that C++ respects its elders and initializes 
  275. its parents prior to itself.  That should be a useful memory aid 
  276. in the use of member initializers.
  277.  
  278. Next, all local class members are initialized in the order in 
  279. which they are declared in the class, not the order in which they 
  280. are declared in the initialization list.  Actually, it would 
  281. probably be good practice to not use the member initializer to 
  282. initialize class members but instead to initialize them in the 
  283. normal constructor code.
  284.  
  285. Finally, after the member initializers are all executed in the 
  286. proper order, the main body of the constructor is executed in the 
  287. normal manner.
  288.  
  289.                                                          Page 9-5
  290.  
  291.            Chapter 9 - Multiple Inheritance and Future Directions
  292.  
  293. USING THE NEW CLASS
  294. -----------------------------------------------------------------
  295. The example program named USEDTTM.CPP uses      =================
  296. the datetime class we just built, and like         USEDTTM.CPP
  297. our previous examples, the main program is      =================
  298. kept very simple and straight forward.  You 
  299. will note that the default constructor is used for the object 
  300. named now, and the constructor with the member initializers is 
  301. used with the objects named birthday and special.  The diligent 
  302. student should have no trouble understanding the remaining code 
  303. in this example.
  304.  
  305.  
  306. FUTURE DIRECTIONS OF C++
  307. -----------------------------------------------------------------
  308. An ANSI committee has been formed to write an ANSI standard for 
  309. C++.  They first met in the Spring of 1990 and are expected to 
  310. release the first draft of the standard sometime in 1994.  The 
  311. goal for the final release is 1996, but until the new standard is 
  312. released, the C++ language is expected to stay fairly stable.  
  313. However, due to the nature of compiler writers and their desire 
  314. to slightly improve their offerings over their competitors, you 
  315. can bet that the language will not remain static during this 
  316. period.
  317.  
  318. Many small changes have been added recently that barely affect 
  319. the casual programmer, or even the heavy user of the language.  
  320. You can be sure that the language will evolve slowly and surely 
  321. into a very usable and reliable language.  There are two areas, 
  322. however, that should be discussed in a little detail because they 
  323. will add so much to the language in future years.  Those two 
  324. topics are parameterized types and exception handling.
  325.  
  326.  
  327. FUTURE DIRECTIONS - PARAMETERIZED TYPES
  328. -----------------------------------------------------------------
  329. Many times, when developing a program, you wish to perform some 
  330. operation on more than one data type.  For example you may wish 
  331. to sort a list of integers, another list of floating point 
  332. numbers, and a list of alphabetic strings.  It seems silly to 
  333. have to write a separate sort function for each of the three 
  334. types when all three are sorted in the same logical way.  With 
  335. parameterized types, you will be able to write a single sort 
  336. routine that is capable of sorting all three of the lists.
  337.  
  338. This is already available in the Ada language as the generic 
  339. package or procedure.  Because it is available in Ada, there is a 
  340. software components industry that provides programmers with 
  341. prewritten and thoroughly debugged software routines that work 
  342. with many different types.  When this is generally available in 
  343. C++, there will be a components industry for C++ and precoded, 
  344. debugged and efficient source code will be available off the 
  345. shelf to perform many of the standard operations.  These 
  346.  
  347.                                                          Page 9-6
  348.  
  349.            Chapter 9 - Multiple Inheritance and Future Directions
  350.  
  351. operations will include such things as sorts, queues, stacks, 
  352. lists, etc.
  353.  
  354. Several compiler writers have included templates in their latest 
  355. compilers.  The next three example programs will illustrate the 
  356. use of templates with Borland's compiler, but may not work with 
  357. other compilers.
  358.  
  359.  
  360. THE FIRST TEMPLATE
  361. -----------------------------------------------------------------
  362. The example program named TEMPLAT1.CPP is the  ==================
  363. first example of the use of a template.  This     TEMPLAT1.CPP
  364. program is so simple it seems silly to even    ==================
  365. bother with it but it will illustrate the use 
  366. of the parameterized type.
  367.  
  368. The template is given in lines 4 through 8 with the first line 
  369. indicating that it is a template with a single type to be 
  370. replaced, the type ANY_TYPE.  This type can be replaced by any 
  371. type which can be used in the comparison operation in line 7.  If 
  372. you have defined a class, and you have overloaded the operator 
  373. ">", then this template can be used with objects of your class.  
  374. Thus, you do not have to write a maximum function for each type 
  375. or class in your program.
  376.  
  377. This function is included automatically for each type it is 
  378. called with in the program, and the code itself should be very 
  379. easy to understand.
  380.  
  381. The diligent student should realize that nearly the same effect 
  382. can be achieved through use of a macro, except that when a macro 
  383. is used, the strict type checking is not done.  Because of this 
  384. and because of the availability of the inline method capability 
  385. in C++, the use of macros is essentially non-existent by 
  386. experienced C++ programmers.
  387.  
  388.  
  389. A CLASS TEMPLATE
  390. -----------------------------------------------------------------
  391. The example program named TEMPLAT2.CPP is a    ==================
  392. little more involved since it provides a          TEMPLAT2.CPP
  393. template for an entire class rather than a     ==================
  394. single function.  The template code is given 
  395. in lines 6 through 16 and a little study will show that this is 
  396. an entire class definition.  The diligent student will recognize 
  397. that this is a very weak stack class since there is nothing to 
  398. prevent popping data from an empty stack, and there is no 
  399. indication of a full stack.  Our intent, however, is to 
  400. illustrate the use of the parameterized type and to do so using 
  401. the simplest class possible.
  402.  
  403.  
  404.  
  405.                                                          Page 9-7
  406.  
  407.            Chapter 9 - Multiple Inheritance and Future Directions
  408.  
  409. In the main program we create an object named int_stack in line 
  410. 25 which will be a stack designed to store integers, and another 
  411. object named float_stack in line 26 which is designed to store 
  412. float type values.  In both cases, we enclose the type we desire 
  413. this object to work with in "<>" brackets, and the system creates 
  414. the object by first replacing all instances of ANY_TYPE with the 
  415. desired type, then creating the object of that type.  You will 
  416. note that any type can be used that has an assignment capability 
  417. since lines 12 and 13 use the assignment operator on the 
  418. parameterized type.
  419.  
  420. Even though the strings are all of differing lengths, we can even 
  421. use the stack to store a stack of strings if we only store a 
  422. pointer to the strings and not the entire string.  This is 
  423. illustrated in the object named string_stack declared in line 27 
  424. and used later in the program.
  425.  
  426. This program should be fairly easy for you to follow if you spend 
  427. a bit of time studying it.  You should compile and run it if you 
  428. have a compiler that will handle this new construct.
  429.  
  430.  
  431. REUSING THE STACK CLASS
  432. -----------------------------------------------------------------
  433. The program named TEMPLAT3.CPP uses the same   ==================
  434. class with the template as defined in the         TEMPLAT3.CPP
  435. last program but in this case, it uses the     ==================
  436. date class developed earlier as the stack 
  437. members.  More specifically, it uses a pointer to the date class 
  438. as the stack member. Because class assignment is legal, you could 
  439. also store the actual class in the stack rather than just the 
  440. pointer to it.  To do so however, would be very inefficient since 
  441. the entire class would be copied into the stack each time it is 
  442. pushed and the entire class would be copied out again when it was 
  443. popped.  Use of the pointer is a little more general, so it was 
  444. illustrated here for your benefit.
  445.  
  446. All three of the previous programs can be compiled and executed 
  447. if you have a compiler that supports templates.  Parameterized 
  448. types are a part of the C++ specification, but are not yet 
  449. included in all implementations.
  450.  
  451.  
  452. FUTURE DIRECTIONS - EXCEPTION HANDLING
  453. -----------------------------------------------------------------
  454. A future version of C++ will have some form of exception handling 
  455. to allow the programmer to trap errors and prevent the system 
  456. from completely shutting down when a fatal error occurs.  The 
  457. Ada language allows the programmer to trap any error that occurs, 
  458. even system errors, execute some recovery code, and continue on 
  459. with the program execution in a very well defined way.  Bjarne 
  460. Stroustrup, working in conjunction with the ANSI-C++ committee, 
  461. has announced that some form of exception handling will be 
  462.  
  463.                                                          Page 9-8
  464.  
  465.            Chapter 9 - Multiple Inheritance and Future Directions
  466.  
  467. implemented but he has not stated exactly what form it would take 
  468. as of this writing.
  469.  
  470.  
  471. WHAT SHOULD BE YOUR NEXT STEP?
  472. -----------------------------------------------------------------
  473. Once again, we have reached a major milestone in C++ programming.  
  474. With the ability to use inheritance, you have nearly all of the 
  475. tools you need to effectively use the object oriented programming 
  476. techniques of C++ and you would do well to stop studying again 
  477. and begin programming.  The only topic left with C++ is virtual 
  478. methods which are used for dynamic binding or polymorphism.  This 
  479. will be covered in the next two chapters.  The vast majority of 
  480. all programming can be done without dynamic binding, and in 
  481. attempting to force it into every program, you could wind up with 
  482. an unreadable mess, so you should approach it slowly.
  483.  
  484.  
  485.  
  486.  
  487.  
  488.  
  489.  
  490.  
  491.  
  492.  
  493.  
  494.  
  495.  
  496.  
  497.  
  498.  
  499.  
  500.  
  501.  
  502.  
  503.  
  504.  
  505.  
  506.  
  507.  
  508.  
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.                                                          Page 9-9
  522.