home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / info / c_tutorg / chap09.txt < prev    next >
Encoding:
Text File  |  1992-05-24  |  21.5 KB  |  448 lines

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