home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / c / tutorial / cpptutor / text / chap11.txt < prev    next >
Encoding:
Text File  |  1994-05-15  |  19.6 KB  |  406 lines

  1.  
  2.  
  3.  
  4.                                                        Chapter 11
  5.                                            MORE VIRTUAL FUNCTIONS
  6.  
  7. This chapter will actually be a continuation of the topics 
  8. covered in the last chapter but this will be a fuller explanation 
  9. of what virtual functions are and how they can be used in a 
  10. program.  We will present a simple database program with a 
  11. virtual function to show how it can be used, then we will go on 
  12. to illustrate a more complex use of the virtual function in a 
  13. manner that finally illustrates its utility and reason for 
  14. existence.
  15.  
  16.  
  17. HOW TO START AN OOP PROJECT
  18. -----------------------------------------------------------------
  19. The observant student will notice that we begin our use of object 
  20. oriented programming by identifying an object, or in this case, a 
  21. class of objects and even some subordinate objects, which we 
  22. completely define.  When we get to the main program we then have 
  23. a simple job with the remaining needs and they are completed 
  24. using standard procedural programming techniques which we are 
  25. familiar with.  This is the way to begin any object oriented 
  26. programming project, by first identifying a few objects that can 
  27. be separated conveniently from the rest of the code, programming 
  28. them, then writing the main program.  It should be added that, 
  29. for your first project using objects, do not try to make 
  30. everything an object.  Select a few objects and after gaining 
  31. experience with object oriented programming techniques, use more 
  32. objects on future projects.  Most programmers use too many 
  33. objects for their first project and write very obtuse, 
  34. unreadable code.
  35.  
  36.  
  37. THE PERSON HEADER FILE
  38. -----------------------------------------------------------------
  39. Examine the file named PERSON.H for the        ==================
  40. definition file for the person class.  This         PERSON.H
  41. class definition should cause you no problem   ==================
  42. to understand since there is nothing new 
  43. here.  The only thing that should be mentioned about this class 
  44. is that the protected mode is used for the variables so that they 
  45. are readily available in the derived classes which will inherit 
  46. this class.
  47.  
  48.  
  49. THE PERSON IMPLEMENTATION
  50. -----------------------------------------------------------------
  51. The implementation for the person class is     ==================
  52. given here and it is a little strange in the       PERSON.CPP
  53. way it is written and used.  The intent of     ==================
  54. this program is that the virtual method named 
  55. display() in this file will never be used, but it is required by 
  56.  
  57.                                                         Page 11-1
  58.  
  59.                               Chapter 11 - More Virtual Functions
  60.  
  61. the C++ compiler to be used for a default in case some of the 
  62. subclasses do not have this function available.  In the main 
  63. program we will be careful to never call this function due to the 
  64. nature of the program we are writing.  Keep in mind that C++ 
  65. requires an implementation of all virtual functions even if they 
  66. are never used.  In this case the message is obviously intended 
  67. to be output as an error message.
  68.  
  69. Be sure to compile this program prior to going on to the next 
  70. class definitions.
  71.  
  72.  
  73. THE SUPERVISOR HEADER
  74. -----------------------------------------------------------------
  75. The file named SUPERVSR.H contains the class   ==================
  76. definitions for the three derived classes,         SUPERVSR.H
  77. supervisor, programmer, and secretary.  These  ==================
  78. were all placed in a single file for two 
  79. reasons.  The first reason is to simply illustrate to you that 
  80. this can be done, and secondly, to allow some of the files to be 
  81. combined on the disk and to require fewer compilations by you 
  82. prior to executing the resulting program.  This is actually a 
  83. good way to combine these files since they are all derived 
  84. classes of a common class.  It is a matter of style or personal 
  85. taste.
  86.  
  87. You will notice that all three of these classes contain a method 
  88. named display() and all have the same return value of void, and 
  89. all have the same number of parameters as the parent class's 
  90. method of the same name.  All of this equality is required 
  91. because they will all be called by the same call statement.  You 
  92. will also notice that the other method in each class has the same 
  93. name, but different numbers and types of formal parameters which 
  94. prevents this method from being used as a virtual method.
  95.  
  96. The remainder of this file is simple and you should be able to 
  97. read the code and understand it completely.  Once again, this 
  98. file cannot be compiled or executed.
  99.  
  100.  
  101. THE SUPERVISOR IMPLEMENTATION
  102. -----------------------------------------------------------------
  103. The file named SUPERVSR.CPP contains the       ==================
  104. implementation for the three classes.  If         SUPERVSR.CPP
  105. you spend a little time studying the code,     ==================
  106. you will find that each of the methods named 
  107. init_data() simply initializes all fields to those passed in as 
  108. the actual arguments in a very simple manner.  The method named 
  109. display(), however, outputs the stored data in different ways for 
  110. each class since the data is so different in each of the classes.  
  111. Even though the interface to these three methods is identical, 
  112. the actual code is significantly different.  There is no reason 
  113. code besides output could not have been used, but the output is 
  114.  
  115.                                                         Page 11-2
  116.  
  117.                               Chapter 11 - More Virtual Functions
  118.  
  119. so visible when the program is executed that it was chosen for 
  120. this illustration.
  121.  
  122. This file should be compiled at this time in preparation for the 
  123. next example program which will use all four classes as defined 
  124. in these four files.
  125.  
  126.  
  127. THE FIRST CALLING PROGRAM
  128. -----------------------------------------------------------------
  129. The file named EMPLOYEE.CPP is the first       ==================
  130. program that uses the classes developed in        EMPLOYEE.CPP
  131. this chapter, and you will find that it is a   ==================
  132. very simple program.
  133.  
  134. We begin with an array of ten pointers, each pointing to the base 
  135. class.  As you recall from the last chapter, this is very 
  136. important when using virtual functions, the pointer must point to 
  137. the base class.  The pointers that will be stored in this array 
  138. will all point to objects of the derived classes however.  When 
  139. we use the resulting pointers to refer to the methods, the system 
  140. will choose the method at run time, not at compile time as nearly 
  141. all of our other programs have been doing.
  142.  
  143. We allocate six objects in lines 16 through 39, initialize them 
  144. to some values using the methods named init_data(), then assign 
  145. the pointers to the members of the array of pointers to person.  
  146. Finally, in lines 41 and 42, we call the methods named display() 
  147. to display the stored data on the monitor.  You will notice that 
  148. even though we only use one method call in line 42, we actually 
  149. send messages to each of the three methods named display() in the 
  150. subclasses.  This is true dynamic binding because if we were to 
  151. change the values of some of the pointers in the array, we would 
  152. then call different methods with the same pointers.
  153.  
  154. Be sure to compile and execute this program before continuing on 
  155. in this chapter.  You will recall that the linking step requires 
  156. you to combine several files in order to satisfy all system 
  157. calls.  After you have done that, we will use the same objects in 
  158. another way to show how they can be reused.
  159.  
  160.  
  161. THE LINKED LIST CLASS
  162. -----------------------------------------------------------------
  163. Examination of the file named ELEMLIST.H will  ==================
  164. reveal the definition of two more classes          ELEMLIST.H
  165. which will be used to build a linked list of   ==================
  166. employees to illustrate a more practical way 
  167. to use the dynamic binding we have been studying in this chapter.
  168. The two classes were put in the same file because they work 
  169. together so closely and neither is of much value without the 
  170. other.  You will notice that the elements of the linked list do 
  171. not contain any data, only a pointer to the person class that we 
  172.  
  173.                                                         Page 11-3
  174.  
  175.                               Chapter 11 - More Virtual Functions
  176.  
  177. developed for the last program, so that the linked list will be 
  178. composed of elements of the person class without modifying the 
  179. class itself.
  180.  
  181. There are two interesting constructs used here that must be 
  182. pointed out before going on to the next program.  The first is 
  183. the partial declaration given in line 8 which allows us to refer 
  184. to the class named employee_list before we actually define it.  
  185. The complete declaration for the class is given in lines 22 
  186. through 29.  The second construct of interest is the friend class 
  187. listed in line 17 where we give the entire class named 
  188. employee_list free access to the variables which are a part of 
  189. the employee_element class.  This is necessary because the method 
  190. named add_person() must access the pointers contained in 
  191. employee_element.  We could have defined an additional method as 
  192. a part of employee_element and used this method to refer to the 
  193. pointers but it was felt that these two classes work so well 
  194. together that it is not a problem to open a window between the 
  195. classes.  We still have complete privacy from all other programs 
  196. and classes declared as parts of this program.
  197.  
  198. Note that the single method included in the employee_element 
  199. class is implemented in inline code.  Two of the methods of 
  200. employee_list are still open so we need an implementation for 
  201. this class.
  202.  
  203.  
  204. THE LINKED LIST IMPLEMENTATION
  205. -----------------------------------------------------------------
  206. The file named ELEMLIST.CPP is the             ==================
  207. implementation for the linked list classes        ELEMLIST.CPP
  208. and should be self explanatory if you          ==================
  209. understand how a singly linked list operates.  
  210. All new elements are added to the end of the current list.  This 
  211. was done to keep it simple but an alphabetic sorting mechanism 
  212. could be added to sort the employees by name if desired.
  213.  
  214. The method to display the list simply traverses the list and 
  215. calls the method named display() in line 30 once for each element 
  216. of the list.
  217.  
  218. It is important for you to take notice that in this entire class, 
  219. there is no mention made of the existence of the three derived 
  220. classes, only the base class named person is mentioned.  The 
  221. linked list therefore has no hint that the three subclasses even 
  222. exist, but in spite of that, we will see this class send messages 
  223. to the three subclasses as they are passed through this logic.  
  224. That is exactly what dynamic binding is, and we will have a 
  225. little more to say about it after we examine the calling program.
  226.  
  227.  
  228.  
  229.  
  230.  
  231.                                                         Page 11-4
  232.  
  233.                               Chapter 11 - More Virtual Functions
  234.  
  235. USING THE LINKED LIST
  236. -----------------------------------------------------------------
  237. At this time you should examine the example    ==================
  238. program named EMPLOYE2.CPP for our best           EMPLOYE2.CPP
  239. example of dynamic binding in this tutorial,   ==================
  240. yet the program is kept very simple.
  241.  
  242. This program is very similar to the example program named 
  243. EMPLOYEE.CPP with a few changes to better illustrate dynamic 
  244. binding.  In line 7 we declare an object of the class 
  245. employee_list to begin our linked list.  This is the only copy of 
  246. the list we will need for this program.  For each of the 
  247. elements, we allocate the data, fill it, and send it to the 
  248. linked list to be added to the list where we allocate another 
  249. linked list element to point to the new data, and add it to the 
  250. list.  The code is very similar to the last program down through 
  251. line 40.
  252.  
  253. In line 43 we send a message to the display_list() method which 
  254. outputs the entire list of personnel.  You will notice that the 
  255. linked list class defined in the files named ELEMLIST.H and 
  256. ELEMLIST.CPP are never informed in any way that the subclasses 
  257. even exist but they dutifully pass the pointers to these 
  258. subclasses to the correct methods and the program runs as 
  259. expected.
  260.  
  261. If you changed PERSON.H to use a pure virtual function, it will 
  262. still work with this program just as we discussed earlier.
  263.  
  264.  
  265. WHAT GOOD IS ALL OF THIS?
  266. -----------------------------------------------------------------
  267. Now that we have the program completely debugged and working, 
  268. suppose that we wished to add another class to the program.  For 
  269. example, suppose we wished to add a class named consultant 
  270. because we wished to include some consultants in our business.  
  271. We would have to write the class of course and the methods within 
  272. the classes, but the linked list doesn't need to know that the 
  273. new class is added, so it doesn't require any changes in order to 
  274. update the program to handle consultant class objects.  In this 
  275. particular case, the linked list is very small and easy to 
  276. understand, but suppose the code was very long and complex as 
  277. with a large database.  It would be very difficult to update 
  278. every reference to the subclasses and add another subclass to 
  279. every list where they were referred to, and this operation would 
  280. be very error prone.  In the present example program, the linked 
  281. list would not even have to be recompiled in order to add the new 
  282. functionality.
  283.  
  284. It should be clear to you that it would be possible to actually 
  285. define new types, dynamically allocate them, and begin using them 
  286. even while the program was executing if we properly partitioned 
  287. the code into executable units operating in parallel.  This would 
  288.  
  289.                                                         Page 11-5
  290.  
  291.                               Chapter 11 - More Virtual Functions
  292.  
  293. not be easy, but it could be done for a large database that was 
  294. tracking the inventory for a large retail store, or even for an 
  295. airlines reservation system.  You probably have little difficulty 
  296. understanding the use of dynamically allocated memory for data, 
  297. but dynamically allocating classes or types is new and difficult 
  298. to grasp, but the possibility is there with dynamic binding.
  299.  
  300.  
  301. AN APPLICATION FRAMEWORK
  302. -----------------------------------------------------------------
  303. The example program named APPFRAM1.CPP         ==================
  304. illustrates the method used to write an           APPFRAM1.CPP
  305. application framework.  If you do much         ==================
  306. serious programming, you will encounter one 
  307. because they provide so many benefits for the MS Windows 
  308. programmer.  There are application frameworks available for DOS 
  309. too, so most programmers should be familiar with them.
  310.  
  311. The class named CForm is the base class for our trivial but 
  312. important example, and it consists of four methods but no data 
  313. members.  The diligent student will note that the method named 
  314. display_form calls the other three members to actually do the 
  315. work of displaying our little form on the monitor.  There is 
  316. nothing magic about this program except that it is the framework 
  317. for a very interesting concept used by all of the application 
  318. frameworks currently available.  Note that three of the methods 
  319. are declared as virtual in lines 8 through 10.
  320.  
  321. The interesting part occurs when we inherit the class into our 
  322. new class named CMyForm in line 22 and write new methods for two 
  323. of the base class methods.  We have inherited as much 
  324. functionality from the base class as we liked and wrote new 
  325. methods for those that didn't serve our purpose as originally 
  326. written.  When we finally execute an object of the new class in 
  327. line 34 of the main program, we do indeed use part of the base 
  328. class, and override those parts that we explicitly wrote methods 
  329. for.
  330.  
  331. This is not too appealing in such a simple example, but if we 
  332. consider how this is used in a real application framework, it is 
  333. a very useful construct.  The writer of an application framework 
  334. will write a complete program that does all of the necessary 
  335. housekeeping and windows maintenance chores and partition it in a 
  336. number of virtual methods much like we did here.  Of course, the 
  337. framework will be composed of a large body of code to do all of 
  338. those chores.  In much the same manner that we picked which parts 
  339. of this little form display program we wished to use and which to 
  340. override, we pick those parts of the framework that we wish to 
  341. keep as is and override those parts that we wish change.  A large 
  342. body of code is therefore already written for us and ready for 
  343. our use.
  344.  
  345.  
  346.  
  347.                                                         Page 11-6
  348.  
  349.                               Chapter 11 - More Virtual Functions
  350.  
  351. The application framework can include many other preprogrammed 
  352. functions ready for our use, such as editor code for edit 
  353. windows, data verification code for dialogue windows, and ready 
  354. to use message window code.  You will find it to be a very 
  355. rewarding study to spend time examining the capabilities of one 
  356. or more of the commercially available application frameworks.
  357.  
  358.  
  359. A PURE VIRTUAL FUNCTION
  360. -----------------------------------------------------------------
  361. The example program named APPFRAM2.CPP         ==================
  362. illustrates a pure virtual function.  A pure      APPFRAM2.CPP
  363. virtual function is declared by assigning the  ==================
  364. value of zero to the function as illustrated 
  365. in line 9.  A class containing one or more pure virtual functions 
  366. cannot be used to define an object.  The class is therefore only 
  367. useful as a base class to be inherited into a useable derived 
  368. class.  It is sometimes called an abstract class.
  369.  
  370. Every derived class must include a function for each pure virtual 
  371. function that is inherited from the base class.  This assures 
  372. that there will be a function available for each call and none 
  373. will ever need to be answered by the base class, which it cannot 
  374. do since it does not have an implementation for a pure virtual 
  375. function.  You cannot create an object of any class which 
  376. contains one or more pure virtual functions, because there is 
  377. nothing to answer a message if one is sent to the pure virtual 
  378. method.  The compiler will enforce the two rules mentioned in 
  379. this paragraph.  If a class inherits an abstract class without 
  380. providing an override for the pure virtual function, then it too 
  381. becomes an abstract class and cannot be used to define an object.
  382.  
  383. You will notice that the present example uses an abstract base 
  384. class which makes it illegal to use an object of the base class 
  385. as we did in the last example program.  For that reason, some of 
  386. the main program is commented out.
  387.  
  388. You will find abstract classes used in many commercially 
  389. available libraries and in application frameworks.  Be sure to 
  390. compile and execute this program, then make some modifications to 
  391. see what the compiler indicates if you try to violate some of the 
  392. rules we have delineated here.
  393.  
  394. PROGRAMMING EXERCISE
  395. -----------------------------------------------------------------
  396. 1.  Add a new class named consultant to the files named 
  397.     SUPERVSR.H and SUPERVSR.CPP, then add code to EMPLOYE2.CPP to 
  398.     exercise the new class.  Note that you do not need to 
  399.     recompile the linked list class in order to execute the new 
  400.     code and use the new class.  Even without recompiling the 
  401.     linked list class it is capable of storing and passing the 
  402.     new class of data provided of course that the new class is 
  403.     referred to using a pointer to the parent class.
  404.  
  405.                                                         Page 11-7
  406.