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

  1.  
  2.  
  3.  
  4.                                                         Chapter 5
  5.                                                     ENCAPSULATION
  6.  
  7. As mentioned in Chapter 1, object oriented programming will seem 
  8. very unnatural to a programmer with a lot of procedural 
  9. programming experience.  This chapter is the beginning of the 
  10. definition of object oriented programming, and we will study the 
  11. topic of encapsulation which is a "divide and conquer" technique.  
  12. As we stated earlier, there are a lot of new terms used with 
  13. object oriented programming.  Don't be intimidated by the new 
  14. terminology, we will study the terms one at a time in a 
  15. meaningful order.
  16.  
  17. Encapsulation is the process of forming objects which we will 
  18. discuss throughout this chapter.  An encapsulated object is often 
  19. called an abstract data type and it is what object oriented 
  20. programming is all about.  Without encapsulation, which involves 
  21. the use of one or more classes, there is no object oriented 
  22. programming.  Of course there are other topics concerning object 
  23. oriented programming, but this is the cornerstone.
  24.  
  25.  
  26. WHY BOTHER WITH ENCAPSULATION?
  27. -----------------------------------------------------------------
  28. We need encapsulation because we are human, and humans make 
  29. errors.  When we properly encapsulate some code, we actually 
  30. build an impenetrable wall to protect the contained code from 
  31. accidental corruption due to the silly little errors that we are 
  32. all prone to make.  We also tend to isolate errors to small 
  33. sections of code to make them easier to find and fix.  We will 
  34. have a lot more to say about the benefits of encapsulation as we 
  35. progress through the tutorial.
  36.  
  37.  
  38. NO INFORMATION HIDING
  39. -----------------------------------------------------------------
  40. The program named OPEN.CPP is a really stupid    ================
  41. program because it does next to nothing, but         OPEN.CPP
  42. it will be the beginning point for our           ================
  43. discussion of encapsulation, otherwise known 
  44. as information hiding.  Information hiding is an important part 
  45. of object oriented programming and you should have a good grasp 
  46. of what it is by the time we finish this chapter.
  47.  
  48. A very simple structure is defined in lines 4 through 6 which 
  49. contains a single int type variable within the structure.  This 
  50. is sort of a silly thing to do, but it will illustrate the 
  51. problem we wish to overcome in this chapter.  Three variables are 
  52. declared in line 10, each of which contains a single int type 
  53. variable and each of the three variables are available for use 
  54. anywhere within the main function.  Each variable can be 
  55. assigned, incremented, read, modified, or have any number of 
  56.  
  57.                                                          Page 5-1
  58.  
  59.                                         Chapter 5 - Encapsulation
  60.  
  61. operations performed on it.  A few of the operations are 
  62. illustrated in lines 13 through 21 and should be self explanatory 
  63. to anyone with a little experience with the C programming 
  64. language.
  65.  
  66. An isolated local variable named piggy is declared and used in 
  67. the same section of code to illustrate that there is nothing 
  68. magic about this code.  Figure 5-1 is a graphical representation 
  69. of the data space after execution of line 16.  Study this simple 
  70. program carefully because it is the basis for beginning our study 
  71. of encapsulation.  Be sure to compile and execute this program, 
  72. then we will go on to the next example program where we will see 
  73. our first example of real information hiding.
  74.  
  75.  
  76. INFORMATION HIDING
  77. -----------------------------------------------------------------
  78. Examine the program named CLAS.CPP for our     ==================
  79. first example of a program with a little            CLAS.CPP
  80. information hiding contained in it.  This      ==================
  81. program is identical to the last one except 
  82. for the way it does a few of its operations.  We will take the 
  83. differences one at a time and explain what is happening.  Keep in 
  84. mind that this is a trivial program and the safeguards built into 
  85. it are not needed for such a simple program but are used here to 
  86. illustrate how to use these techniques in a larger much more 
  87. complicated program.
  88.  
  89. The first difference is that we have a class instead of a 
  90. structure beginning in line 4 of this program.  The only 
  91. difference between a class and a structure is that a class begins 
  92. with a private section whereas a structure begins with a private 
  93. section.  The keyword class is used to declare a class as 
  94. illustrated here.
  95.  
  96. The class named one_datum is composed of the single variable 
  97. named data_store and two functions, one named set() and the other 
  98. named get_value().  A more complete definition of a class is a 
  99. group of variables, and one or more functions that can operate on 
  100. that data.  Stay with us, we will tie this all together in a 
  101. meaningful and useful way very soon.
  102.  
  103.  
  104. WHAT IS A PRIVATE SECTION?
  105. -----------------------------------------------------------------
  106. All data at the beginning of a class defaults to private.  
  107. Therefore, the data at the beginning of the class cannot be 
  108. accessed outside of the class, it is hidden from any outside 
  109. access.  Therefore, the variable named data_store which is a part 
  110. of the object (an object will be defined completely later) named 
  111. dog1 declared in line 23, is not available for use anywhere in 
  112. the main program.  It is as if we have built a "brick wall" 
  113. around the variables to protect them from accidental corruption 
  114.  
  115.                                                          Page 5-2
  116.  
  117.                                         Chapter 5 - Encapsulation
  118.  
  119. by outside programming influences.  It seems a little dumb to 
  120. declare a variable in the main program that we cannot use, but 
  121. that is exactly what we did.  
  122.  
  123. Figure 5-2 is a graphical representation of the class with its 
  124. "brick wall" built around the data to protect it.  You will 
  125. notice the small peep holes we have opened up to allow the user 
  126. to gain access to the functions.  The peep holes were opened by 
  127. declaring the functions in the public section of the class.
  128.  
  129.  
  130. WHAT IS A PUBLIC SECTION?
  131. -----------------------------------------------------------------
  132. A new keyword, public, is introduced in line 6 which states that 
  133. anything following this keyword can be accessed from outside of 
  134. this class.  Because the two functions are defined following the 
  135. keyword public, they are both public and available for use by 
  136. any  calling program that is within the scope of this object.  
  137. This essentially opens two small peepholes in the solid wall of 
  138. protection that we built around the class.  You should keep in 
  139. mind that the private variable is not available to the calling 
  140. program.  Thus, we can only use the variable by calling one of 
  141. the two functions defined within the public part of the class.  
  142. These are called member functions because they are members of the 
  143. class.
  144.  
  145. Since we have declared two functions, we need to define them by 
  146. saying what each function will actually do.  This is done in 
  147. lines 11 through 19 where they are each defined in the normal 
  148. way, except that the class name is prepended onto the function 
  149. name and separated from it by a double colon.  These two function 
  150. definitions are called the implementation of the functions.  The 
  151. class name is required because we can use the same function name 
  152. in other classes and the compiler must know with which class to 
  153. associate each function implementation.
  154.  
  155. One of the key points to be made here is that the private data 
  156. contained within the class is available within the implementation 
  157. of the member functions of the class for modification or reading 
  158. in the normal manner.  You can do anything with the private data 
  159. within the function implementations which are a part of that 
  160. class, but the private data of other classes is hidden and not 
  161. available within the member functions of this class.  This is the 
  162. reason we must prepend the class name to the function names of 
  163. this class when defining them.  Figure 5-3 depicts the data space 
  164. following execution of line 29.
  165.  
  166. It would be well to mention at this point that it is legal to 
  167. include variables and functions in the private part, and 
  168. additional variables and functions in the public part also.  In 
  169. most practical situations, variables are included in only the 
  170. private part and functions are included in only the public part 
  171. of a class definition.  Occasionally, variables or functions are 
  172.  
  173.                                                          Page 5-3
  174.  
  175.                                         Chapter 5 - Encapsulation
  176.  
  177. used in the other part.  This sometimes leads to a very practical 
  178. solution to a particular problem, but in general, the entities 
  179. are used only in the places mentioned.
  180.  
  181. In C++ we have three scopes of variables, local, file and class.  
  182. Local variables are localized to a single function.  File 
  183. variables, those that are defined outside of any function, are 
  184. available anywhere in a file following their definition.  A 
  185. variable with class scope is available anywhere within the scope 
  186. of a class and nowhere else.  The variable named data_store has a 
  187. class scope.
  188.  
  189. You must be very confused by this point since we have given a lot 
  190. of rules but few reasons for doing all of this.  Stay with us and 
  191. you will soon see that there are very practical reasons for doing 
  192. all of this.
  193.  
  194.  
  195. MORE NEW TERMINOLOGY
  196. -----------------------------------------------------------------
  197. As with most new technologies, developers seem to delight in 
  198. making up new names for all aspects of their new pet.  Object 
  199. oriented programming is no different, so we must learn new names 
  200. for some of our old familiar friends if we are going to learn how 
  201. to effectively use it.  To help you learn this new programming 
  202. terminology, we will list a few of them here and begin using them 
  203. in the text to get you used to seeing and using them.  You will 
  204. not understand them all yet, but we need to introduce them early.
  205.  
  206.     A class is a grouping of data and methods (functions).  A 
  207.     class is very much like a structure type as used in ANSI-C, 
  208.     it is only a pattern to be used to create a variable which 
  209.     can be manipulated in a program.
  210.  
  211.     An object is an instance of a class, which is similar to a 
  212.     variable defined as an instance of a type.  An object is 
  213.     what you actually use in a program since it has values and 
  214.     can be changed.
  215.  
  216.     A method is a function contained within the class.  You 
  217.     will find the functions used within a class often referred 
  218.     to as methods in programming literature.
  219.  
  220.     A message is the same thing as a function call.  In object 
  221.     oriented programming, we send messages instead of calling 
  222.     functions.  For the time being, you can think of them as 
  223.     identical.  Later in this tutorial we will see that they 
  224.     are in fact slightly different.
  225.  
  226. With all the new terminology, we will continue our study of the 
  227. program named CLAS.CPP and show you how to use the class.  We can 
  228. now say that we have a class composed of one variable and two 
  229. methods.  The methods operate on the variable contained in the 
  230.  
  231.                                                          Page 5-4
  232.  
  233.                                         Chapter 5 - Encapsulation
  234.  
  235. class when they receive messages to do so.  In this tutorial we 
  236. will use the terms object and variable interchangeably because 
  237. both names are very descriptive of what the object really is.
  238.  
  239. This is a small point but it could be easily overlooked.  Lines 7 
  240. and 8 of this program are actually the prototypes for the two 
  241. methods, and is our first example of the use of a prototype 
  242. within a class.  This is the reason we spent so much time 
  243. studying prototypes in the last chapter.  You will notice line 7 
  244. which says that the method named set requires one parameter of 
  245. type int and returns nothing, hence the return type is void.  The 
  246. method named get_value() however, according to line 8, has no 
  247. input parameters but returns an int type value to the caller.
  248.  
  249.  
  250. SENDING A MESSAGE
  251. -----------------------------------------------------------------
  252. Following all of the definitions in lines 1 through 19, we 
  253. finally come to the program where we actually use the class.  In 
  254. line 23 we declare three objects of the class one_datum and name 
  255. the objects dog1, dog2, and dog3.  Each object contains a single 
  256. data point which we can set through use of one method or read its 
  257. value through use of the other method, but we cannot directly set 
  258. or read the value of the data point because it is hidden within 
  259. the "block wall" around the class.  In line 26, we send a message 
  260. to the object named dog1 instructing it to set its internal value 
  261. to 12, and even though this looks like a function call, it is 
  262. properly called sending a message to a method.  Remember that the 
  263. object named dog1 has a method associated with it called set() 
  264. that sets its internal value to the actual parameter included 
  265. within the message.  You will notice that the form is very much 
  266. like the means of accessing the elements of a structure.  You 
  267. mention the name of the object with a dot connecting it to the 
  268. name of the method.  In a similar manner, we send a message to 
  269. each of the other two objects dog2 and dog3 to set their values 
  270. to those indicated.
  271.  
  272. Lines 31 and 32 have been commented out because the operations 
  273. are illegal. The variable named data_store is private and 
  274. therefore not available to the code outside of the object 
  275. itself.  It should be obvious, but it will be pointed out that 
  276. the data contained within the object named dog1 is not available 
  277. within the methods of dog2 or dog3 because they are different 
  278. objects.  These rules are all devised to help you develop better 
  279. code more quickly and you will soon see how they help.
  280.  
  281. The other method defined for each object is used in lines 34 
  282. through 36 to illustrate how it can be used.  In each case, 
  283. another message is sent to each object and the returned result is 
  284. output to the monitor via the stream library.
  285.  
  286.  
  287.  
  288.  
  289.                                                          Page 5-5
  290.  
  291.                                         Chapter 5 - Encapsulation
  292.  
  293. USING A NORMAL VARIABLE
  294. -----------------------------------------------------------------
  295. There is another variable named piggy declared and used 
  296. throughout this example program that illustrates that a normal 
  297. variable can be intermixed with the objects and used in the 
  298. normal manner.  The use of this variable should pose no problem 
  299. to you, so after you understand the program, be sure to compile 
  300. and execute it.  It would be a good exercise for you to remove 
  301. the comments from lines 31 and 32 to see what kind of error 
  302. message your compiler issues.
  303.  
  304. This program illustrates information hiding but it will not be 
  305. clear to you that it really does anything worthwhile until we 
  306. study the next two programs.  Be sure to compile and execute this 
  307. program, then remove the comments from lines 31 and 32 as 
  308. suggested to see the error messages issued.
  309.  
  310.  
  311. A PROGRAM WITH PROBLEMS
  312. -----------------------------------------------------------------
  313. Examine the program named OPENPOLE.CPP for an  ==================
  314. example of a program with a few serious           OPENPOLE.CPP
  315. problems that will be overcome in the next     ==================
  316. example program by using the principles of 
  317. encapsulation.
  318.  
  319. We have two structures declared, one being a rectangle and the 
  320. other a pole.  The data fields should be self explanatory with 
  321. the exception of the depth of the flagpole which is the depth it 
  322. is buried in the ground, the overall length of the pole is 
  323. therefore the sum of the length and the depth.
  324.  
  325. Figure 5-4 depicts the data space for this program after 
  326. execution of line 32.  Based on your experience with ANSI-C, you 
  327. should have no problem understanding exactly what this program 
  328. is doing, but you may be a bit confused at the meaning of the 
  329. result found in line 38 where we multiply the height of the 
  330. square with the width of the box.  This is perfectly legal to do 
  331. in ANSI-C or C++, but the result has no earthly meaning because 
  332. the data are for two different entities.  Likewise, the result 
  333. calculated in line 40 is even sillier because the product of the 
  334. height of the square and the depth of the flagpole has absolutely 
  335. no meaning in any physical system we can think up.
  336.  
  337. Wouldn't it be neat if we had a way to prevent such stupid things 
  338. from happening in a large production program.  If we had a good 
  339. program that defined all of the things we can do with a square 
  340. and another program that defined everything we could do with a 
  341. pole, and if the data could be kept mutually exclusive, we could 
  342. prevent these silly things from happening.
  343.  
  344. It should come as no real surprise to you that the next program 
  345. will do just those things for us and do it in a very elegant way.  
  346.  
  347.                                                          Page 5-6
  348.  
  349.                                         Chapter 5 - Encapsulation
  350.  
  351. Before proceeding on to the next example program, you should 
  352. compile and execute this one even though it displays some silly 
  353. results.
  354.  
  355.  
  356. OBJECTS PROTECT DATA
  357. -----------------------------------------------------------------
  358. Examine the program named CLASPOLE.CPP as an   ==================
  359. example of data protection in a very simple       CLASPOLE.CPP
  360. program.  In this program the rectangle is     ==================
  361. changed to a class with the same two 
  362. variables which are now private, and two methods to handle the 
  363. private data.  One method is used to initialize the values of the 
  364. objects created and the other method returns the area of the 
  365. object.  The two methods are defined in lines 12 through 21 in 
  366. the manner described earlier in this chapter.  The pole is left 
  367. as a structure to illustrate that the two can be used together 
  368. and that C++ is truly an extension of ANSI-C.
  369.  
  370. In line 33 we declare two objects, once again named box and 
  371. square, but this time we cannot assign values directly to their 
  372. individual components because they are private elements of the 
  373. class. Figure 5-5 is a graphical illustration of the two objects 
  374. available for use within the calling program.  Lines 36 through 
  375. 38 are commented out for that reason and the messages are sent to 
  376. the objects in lines 40 and 41 to tell them to initialize 
  377. themselves to the values input as parameters.  The flag_pole is 
  378. initialized in the same manner as in the previous program.  Using 
  379. the class in this way prevents us from making the silly 
  380. calculations we did in the last program, because we can only 
  381. calculate the area by using the data stored in one object.  The 
  382. compiler is now being used to prevent the erroneous calculations.  
  383. The end result is that the stupid calculations we did in the last 
  384. program are not possible in this program, so lines 50 through 53 
  385. have been commented out.  Once again, it is difficult to see the 
  386. utility of this in such a simple program.  In a large program, 
  387. using the compiler to enforce the rules can pay off in a big way.
  388.  
  389. Even though the square and the box are both objects of class 
  390. rectangle, their private data is hidden from each other such that 
  391. neither can purposefully or accidentally change the other's data.
  392.  
  393. This is the abstract data type mentioned earlier in this chapter, 
  394. a model with a set of private variables for data storage and a 
  395. set of operations that can be performed on that stored data.  The 
  396. only operations that can be performed on the data are those 
  397. defined by the methods, which prevents many kinds of erroneous or 
  398. silly operations.  Encapsulation and data hiding bind the data 
  399. and procedures, or methods, tightly together and limit the scope 
  400. and visibility of each.  Once again, we have the divide and 
  401. conquer technique in which an object is separated from the rest 
  402. of the code and carefully developed in complete isolation from 
  403.  
  404.  
  405.                                                          Page 5-7
  406.  
  407.                                         Chapter 5 - Encapsulation
  408.  
  409. it.  Only then is it integrated into the rest of the code with a 
  410. few very simple interfaces.
  411.  
  412.  
  413. HAVE YOU EVER USED THIS TECHNIQUE BEFORE?
  414. -----------------------------------------------------------------
  415. A good example of the use of this technique is in the file 
  416. commands you have been using with ANSI-C.  The data in the file 
  417. is only available through the predefined functions provided by 
  418. your compiler writer.  You have no direct access to the actual 
  419. data because it is impossible for you to address the actual data 
  420. stored on the disk.  The data is therefore private data, as far 
  421. as you are concerned, but the available functions are very much 
  422. like methods in C++.  There are two aspects of this technique 
  423. that really count when you are developing software.  First, you 
  424. can get all of the data you really need from the file system 
  425. because the interface is complete, but secondly, you cannot get 
  426. any data that you do not need.  You are prevented from getting 
  427. into the file handling system and accidentally corrupting some 
  428. data stored within it.  You are also prevented from using the 
  429. wrong data because the functions available demand a serial access 
  430. to the data.
  431.  
  432. Another example is in the monitor and keyboard handling routines.  
  433. You are prevented from getting into the workings of them and 
  434. corrupting them accidentally, or on purpose if you have such a 
  435. bent, but once again, you are provided with all of the data 
  436. interfaces that you really need.
  437.  
  438. Suppose you are developing a program to analyze some 
  439. characteristics of flagpoles.  You would not wish to 
  440. accidentally use some data referring to where the flagpole 
  441. program was stored on your hard disk as the height of the 
  442. flagpole, nor would you wish to use the cursor position as the 
  443. flagpole thickness or color.  All code for the flagpole is 
  444. developed alone, and only when it is finished, is it available 
  445. for external use.  When using it, you have a very limited number 
  446. of operations which you can do with the class.  The fact that 
  447. the data is hidden from you protects you from accidentally doing 
  448. such a thing when you are working at midnight to try to meet a 
  449. schedule.  Once again, this is referred to as information hiding 
  450. and is one of the primary advantages of object oriented 
  451. programming over procedural techniques.
  452.  
  453. Based on the discussion given above you can see that object 
  454. oriented programming is not really new, since it has been used in 
  455. a small measure for as long as computers have been popular.  The 
  456. newest development, however, is in allowing the programmer to 
  457. partition his programs in such a way that he too can practice 
  458. information hiding and reduce the debugging time.
  459.  
  460.  
  461.  
  462.  
  463.                                                          Page 5-8
  464.  
  465.                                         Chapter 5 - Encapsulation
  466.  
  467. WHAT DOES THIS COST?
  468. -----------------------------------------------------------------
  469. It should be clear that this technique will cost you something in 
  470. efficiency because every access to the elements of the object 
  471. will require the time and inefficiency of a call to a function, 
  472. or perhaps I should be more proper and refer to it as a method.  
  473. The time saved in building a large program, however, could easily 
  474. be saved in debug time when it comes time to iron out the last 
  475. few bugs.  This is because a program made up of objects that 
  476. closely match the application are much easier to understand than 
  477. a program that does not.
  478.  
  479. This is obviously such a small program that it is silly to try to 
  480. see any gain with this technique.  In a real project however, it 
  481. could be a great savings if one person developed all of the 
  482. details of the rectangle, programmed it, and made it available to 
  483. you to simply use.  This is exactly what has been done for you if 
  484. you consider the video monitor an object.  There is a complete 
  485. set of preprogrammed and debugged routines you can use to make 
  486. the monitor do anything you wish it to do, all you have to do is 
  487. study the interface to the routines and use them, expecting them 
  488. to work.  As we mentioned earlier, it is impossible for you to 
  489. multiply the size of your monitor screen by the depth of the flag 
  490. pole because that information is not available to you to use in a 
  491. corruptible way.
  492.  
  493. After you understand some of the advantages of this style of 
  494. programming, be sure to compile and execute this program.
  495.  
  496.  
  497. CONSTRUCTORS AND DESTRUCTORS
  498. -----------------------------------------------------------------
  499. The file named CONSPOLE.CPP introduces         ==================
  500. constructors and destructors and should be        CONSPOLE.CPP
  501. examined at this time.  This example program   ==================
  502. is identical to the last example except that
  503. a constructor has been added as well as a destructor.  The 
  504. constructor always has the same name as the class itself and is 
  505. declared in line 8, then defined in lines 14 through 18.  The 
  506. constructor is called automatically by the C++ system when the 
  507. object is declared and prevents the use of an uninitialized 
  508. variable.  When the object named box is declared in line 46, the 
  509. constructor is called automatically by the system.  The 
  510. constructor sets the values of height and width each to 6 in the 
  511. object named box.  This is printed out for reference in lines 49 
  512. and 50.  Likewise, when the square is declared in line 46, the 
  513. values of the height and the width of the square are each 
  514. initialized to 6 when the constructor is called automatically.
  515.  
  516. A constructor is defined as having the same name as the class 
  517. itself.  In this case both are named rectangle.  The constructor 
  518. cannot have a return type associated with it because of the 
  519. definition of C++.  It actually has a predefined return type, a 
  520.  
  521.                                                          Page 5-9
  522.  
  523.                                         Chapter 5 - Encapsulation
  524.  
  525. pointer to the object itself, but we will not be concerned about 
  526. this until much later in this tutorial.  Even though both objects 
  527. are assigned values by the constructor, they are initialized in 
  528. lines 58 and 59 to new values and processing continues.  Since we 
  529. have a constructor that does the initialization, we should 
  530. probably rename the method named initialize() something else but 
  531. it illustrates the concept involved here.
  532.  
  533. The destructor is very similar to the constructor except that it 
  534. is called automatically when each of the objects goes out of 
  535. scope.  You will recall that automatic variables have a limited 
  536. lifetime because they cease to exist when the enclosing block in 
  537. which they were declared is exited.  When an object is about to 
  538. be automatically deallocated, its destructor, if one exists, is 
  539. called automatically.  A destructor is characterized as having 
  540. the same name as the class but with a tilde prepended to the 
  541. class name.  A destructor has no return type.
  542.  
  543. A destructor is declared in line 11 and defined in lines 31 
  544. through 35.  In this case the destructor only assigns zeros to 
  545. the variables prior to their being deallocated, so nothing is 
  546. really accomplished.  The destructor is only included for 
  547. illustration of how it is used.  If some blocks of memory were 
  548. dynamically allocated within an object, a destructor should be 
  549. used to deallocate them prior to losing the pointers to them.  
  550. This would return their memory to the free store for further use 
  551. later in the program.
  552.  
  553. It is interesting to note that if a constructor is used for an 
  554. object that is declared prior to the main program, a global 
  555. variable, the constructor will actually be executed prior to the 
  556. execution of the main program.  In like manner, if a destructor 
  557. is defined for such a variable, it will execute following the 
  558. completion of execution of the main program.  This will not 
  559. adversely affect your programs, but it is interesting to make 
  560. note of.
  561.  
  562.  
  563. OBJECT PACKAGING
  564. -----------------------------------------------------------------
  565. Examine the file named BOXES1.CPP for an       ==================
  566. example of how not to package an object for        BOXES1.CPP
  567. universal use.  This packaging is actually     ==================
  568. fine for a very small program, but is meant 
  569. to illustrate to you how to split your program up into smaller, 
  570. more manageable files when you are developing a large program or 
  571. when you are part of a team developing a large system.  The next 
  572. three example programs in this chapter will illustrate the proper 
  573. method of packaging a class.
  574.  
  575. This program is very similar to the last one with the pole 
  576. structure dropped and the class named box.  The class is defined 
  577. in lines 4 through 12, the implementation of the class is given 
  578.  
  579.                                                         Page 5-10
  580.  
  581.                                         Chapter 5 - Encapsulation
  582.  
  583. in lines 15 through 34, and the use of the class is given in 
  584. lines 37 through 50.  With the explanation we gave about the last 
  585. example program, the diligent student should have no problem 
  586. understanding this program in detail.
  587.  
  588.  
  589. INLINE IMPLEMENTATION
  590. -----------------------------------------------------------------
  591. The method in line 10 contains the implementation for the method 
  592. as a part of the declaration because it is very simple, and 
  593. because it introduces another new topic which you will use often 
  594. in C++ programming.  When the implementation is included in the 
  595. declaration, it will be assembled inline wherever this function 
  596. is called leading to much faster code.  This is because there is 
  597. no overhead to accomplish the call to the method.  In some cases 
  598. this will lead to code that is both smaller and faster.  This is 
  599. yet another illustration of the efficiency built into the C++ 
  600. programming language.
  601.  
  602. Compile and execute this program in preparation for our study of 
  603. the next three examples which are a repeat of this program in a 
  604. slightly different form.
  605.  
  606.  
  607. THE CLASS HEADER FILE
  608. -----------------------------------------------------------------
  609. If you examine BOX.H carefully, you will see      ===============
  610. that it is only the class definition.  No              BOX.H
  611. details are given of how the various methods      ===============
  612. are implemented except of course for the 
  613. inline method named get_area().  This gives the complete 
  614. definition of how to use the class with no implementation details.  
  615. You would be advised to keep a hardcopy of this file available as 
  616. we study the next two files.  You will notice that it contains 
  617. lines 4 through 12 of the previous example program named 
  618. BOXES1.CPP.  This is called the class header file and cannot be 
  619. compiled or executed.
  620.  
  621.  
  622. THE CLASS IMPLEMENTATION FILE
  623. -----------------------------------------------------------------
  624. Examine the file named BOX.CPP for the          =================
  625. implementation of the methods declared in            BOX.CPP
  626. the class header file.  Notice that the class   =================
  627. header file is included into this file in 
  628. line 2 which contains the prototypes for its methods and the 
  629. definitions of the variables to be manipulated.  The code from 
  630. lines 15 through 34 of BOXES1.CPP is contained in this file which 
  631. is the implementation of the methods declared in the class named 
  632. box.
  633.  
  634. This file can be compiled but it cannot be executed because there 
  635. is no main entry point which is required for all ANSI-C or C++ 
  636.  
  637.                                                         Page 5-11
  638.  
  639.                                         Chapter 5 - Encapsulation
  640.  
  641. programs.  When it is compiled, the object code will be stored in 
  642. the current directory and available for use by other programs.  
  643. It should be noted here that the result of compilation is usually 
  644. referred to as an object file because it contains object code.  
  645. This use of the word object has nothing to do with the word 
  646. object as used in object oriented programming.  It is simply a 
  647. matter of overloading the use of the word.  The practice of 
  648. referring to the compiled result as an object file began long 
  649. before the technique of object oriented programming was ever 
  650. considered.
  651.  
  652. The separation of the definition and the implementation is a 
  653. major step forward in software engineering.  The definition file 
  654. is all the user needs in order to use this class effectively in a 
  655. program.  He needs no knowledge of the actual implementation of 
  656. the methods.  If he had the implementation available, he may 
  657. study the code and find a trick he could use to make the overall 
  658. program slightly more efficient, but this would lead to 
  659. nonportable software and possible bugs later if the implementor 
  660. changed the implementation without changing the interface.  The 
  661. purpose of object oriented programming is to hide the 
  662. implementation in such a way that the implementation can not 
  663. affect anything outside of its own small and well defined 
  664. boundary or interface.
  665.  
  666. You should compile this implementation file now and we will use 
  667. the result with the next example program.
  668.  
  669.  
  670. USING THE BOX OBJECT
  671. -----------------------------------------------------------------
  672. Examine the file named BOXES2.CPP and you      ==================
  673. will find that the class we defined                BOXES2.CPP
  674. previously is used within this file.  In       ==================
  675. fact, these last three programs taken 
  676. together are identical to the program named BOXES1.CPP studied 
  677. earlier.  The BOX.H file is included here, in line 3, since the 
  678. definition of the box class is needed to declare three objects 
  679. and use their methods.  You should have no trouble seeing that 
  680. this is a repeat of the previous program and will execute in 
  681. exactly the same way.  There is a big difference in BOXES1.CPP 
  682. and BOXES2.CPP as we will see shortly.
  683.  
  684. A very important distinction must be made at this point.  We are 
  685. not merely calling functions and changing the terminology a 
  686. little to say we are sending messages.  There is an inherent 
  687. difference in the two operations.  Since the data for each object 
  688. is tightly bound up in the object, there is no way to get to the 
  689. data except through the methods and we send a message to the 
  690. object telling it to perform some operation based on its 
  691. internally stored data.  However, whenever we call a function, we 
  692. take along the data for it to work with as parameters since it 
  693. doesn't contain its own data.
  694.  
  695.                                                         Page 5-12
  696.  
  697.                                         Chapter 5 - Encapsulation
  698.  
  699.  
  700. Be sure to compile and execute this program, but when you come to 
  701. the link step, you will be required to link this program along 
  702. with the result of the compilation when you compiled the class 
  703. named box.  The file is probably named BOX.OBJ that must be 
  704. linked with this file.  You may need to consult the documentation 
  705. for your C++ compiler to learn how to do this.  Even if it seems 
  706. to be a lot of trouble to learn how to link several files 
  707. together, it will be worth your time to do so now because we will 
  708. be linking several more multifile C++ programs in the remainder 
  709. of this tutorial.
  710.  
  711. Depending on your compiler, this is your first opportunity to use 
  712. either a project file, or the "make" facility included with your 
  713. compiler.  Regardless of which C++ compiler you are using, it 
  714. would pay you to stop and learn how to use the multifile 
  715. technique provided with your compiler because you will need to 
  716. use it several times before the end of this tutorial.  The nature 
  717. of C++ tends to drive the programmer to use many files for a 
  718. given programming project and you should develop the habit early.
  719.  
  720.  
  721. INFORMATION HIDING
  722. -----------------------------------------------------------------
  723. The last three example programs illustrate a method of 
  724. information hiding that can have a significant impact on the 
  725. quality of software developed for a large project.  Since the 
  726. only information the user of the class really needs is the class 
  727. header, that is all he needs to be given.  The details of 
  728. implementation can be kept hidden from him to prevent him from 
  729. studying the details and possibly using a quirk of programming to 
  730. write some rather obtuse code.  Since he doesn't know exactly 
  731. what the implementor did, he must follow only the definition 
  732. given in the header file.  This can have a significant impact on 
  733. a large project.  As mentioned earlier, accidental corruption of 
  734. data is prevented also.
  735.  
  736. Another reason for hiding the implementation is economic.  The 
  737. company that supplied you with your C++ compiler gave you many 
  738. library functions but did not supply the source code to the 
  739. library functions, only the interface to each function.  You know 
  740. how to use the file access functions but you do not have the 
  741. details of implementation, nor do you need them.  Likewise a 
  742. class library industry can develop which supplies users with 
  743. libraries of high quality, completely developed and tested 
  744. classes, for a licensing fee of course.  Since the user only 
  745. needs the interface defined, he can be supplied with the 
  746. interface and the object (compiled) code for the class and can 
  747. use it in any way he desires.  The suppliers source code is 
  748. protected from accidental or intentional compromise and he can 
  749. maintain complete control over it.
  750.  
  751.  
  752.  
  753.                                                         Page 5-13
  754.  
  755.                                         Chapter 5 - Encapsulation
  756.  
  757. It is very important that you understand the principles covered 
  758. in this chapter before proceeding on to the next chapter.  If you 
  759. feel you are a little weak in any of the areas covered here, you 
  760. should go over them again before proceeding on.  A point that 
  761. should be made here that may be obvious to you, is that it 
  762. requires a considerable amount of forethought to effectively use 
  763. classes.
  764.  
  765.  
  766. ABSTRACT DATA TYPES
  767. -----------------------------------------------------------------
  768. We mentioned the abstract data type at the beginning of this 
  769. chapter and again briefly midway through, and it is time to 
  770. describe it a little more completely.  An abstract data type is a 
  771. group of data, each of which can store a range of values, and a 
  772. set of methods or functions that can operate on that data.  Since 
  773. the data are protected from any outside influence, it is 
  774. protected and said to be encapsulated.  Also, since the data is 
  775. somehow related, it is a very coherent group of data that may be 
  776. highly interactive with each other, but with little interaction 
  777. outside the scope of its class.
  778.  
  779. The methods, on the other hand, are coupled to the outside world 
  780. through the interface, but there are a limited number of contacts 
  781. with the outside world and therefore a weak coupling with the 
  782. outside.  The object is therefore said to be loosely coupled to 
  783. the outside world.  Because of the tight coherency and the loose 
  784. coupling, ease of maintenance of the software is greatly 
  785. enhanced.  The ease of maintenance may be the greatest benefit of 
  786. object oriented programming.
  787.  
  788. It may bother you that even though the programmer may not use the 
  789. private variables directly outside of the class, they are in 
  790. plain sight and he can see what they are and can probably make a 
  791. good guess at exactly how the class is implemented.  The 
  792. variables could have been hidden completely out of sight in 
  793. another file, but because the designers of C++ wished to make the 
  794. execution of the completed application as efficient as possible, 
  795. the variables were left in the class definition where they can be 
  796. seen but not used.
  797.  
  798.  
  799. FRIEND FUNCTIONS
  800. -----------------------------------------------------------------
  801. A function outside of a class can be defined to be a friend 
  802. function by the class which gives the friend free access to the 
  803. private members of the class.  This in effect, opens a small hole 
  804. in the protective shield of the class, so it should be used very 
  805. carefully and sparingly.  There are cases where it helps to make 
  806. a program much more understandable and allows controlled access 
  807. to the data.  Friend functions will be illustrated in some of the 
  808. example programs later in this tutorial.  It is mentioned here 
  809. for completeness of this section.  A single isolated function can 
  810.  
  811.                                                         Page 5-14
  812.  
  813.                                         Chapter 5 - Encapsulation
  814.  
  815. be declared as a friend, as well as members of other classes, and 
  816. even entire classes can be given friend status if needed in a 
  817. program.  Neither a constructor nor a destructor can be a friend 
  818. function.
  819.  
  820.  
  821. THE struct IN C++
  822. -----------------------------------------------------------------
  823. The struct is still useable in C++ and operates just like it does 
  824. in ANSI-C with one addition.  You can include methods in a 
  825. structure that operate on data in the same manner as in a class, 
  826. but methods and data are automatically defaulted to be public at 
  827. the beginning of a structure.  Of course you can make any of the 
  828. data or methods private by defining a private section within the 
  829. structure.  The structure should be used only for constructs that 
  830. are truly structures.  If you are building even the simplest 
  831. objects, you are advised to use classes to define them.
  832.  
  833.  
  834. A VERY PRACTICAL CLASS
  835. -----------------------------------------------------------------
  836. The examples of encapsulation used in this chapter have all been 
  837. extremely simple in order to illustrate the mechanics of 
  838. encapsulation.  Since it would be expedient to study a larger 
  839. example, the date class is given for your instruction.  The date 
  840. class is a complete nontrivial class which can be used in any 
  841. program to get the current date and print it as an ASCII string 
  842. in any of four predefined formats.  It can also be used to store 
  843. any desired date and format it for display.
  844.  
  845. Examine the file named DATE.H which is the       ================
  846. header file for the date class.  This file is         DATE.H
  847. so well commented that we don't have much        ================
  848. else to say about it.  If you understand the 
  849. principles covered in this chapter you should have no problem 
  850. understanding this class.  One thing that is new to you is the 
  851. reserved word protected which is used in line 12.  We will define 
  852. this word in a couple of chapters.  Until then, pretend that it 
  853. means the same thing as private and you will be close enough for 
  854. this present example.  The code in lines 8 and 9 along with line 
  855. 55 will be explained shortly.  For the present time, simply 
  856. pretend those lines of code are not there.  Also the keyword 
  857. static as used in lines 16 and 17 will be explained later.  These 
  858. new constructs are added because we plan to use this class later 
  859. when we study inheritance.
  860.  
  861. You should spend the time necessary to completely understand this 
  862. class header, with the exception of the new things added, before 
  863. going on to the implementation for this class.
  864.  
  865. The file named DATE.CPP is the implementation    ================
  866. for the date class and once again, there is          DATE.CPP
  867. nothing unusual or difficult about this code.    ================
  868.  
  869.                                                         Page 5-15
  870.  
  871.                                         Chapter 5 - Encapsulation
  872.  
  873. It uses very simple logic to store and format 
  874. the date in a usable manner.  You should study this code until 
  875. you understand it completely before going on to the next example 
  876. which will use the date class in a main program. 
  877.  
  878. The very simple program named USEDATE.CPP is    =================
  879. a main program that uses the date class to         USEDATE.CPP
  880. list the current date and another date on the   =================
  881. monitor.  Once again, you should have no 
  882. problem understanding this program so nothing more will be said 
  883. about it.
  884.  
  885. You should spend the time necessary to understand these three 
  886. files because they are the starting point for a practical track 
  887. in the next few chapters.  This class will be used in conjunction 
  888. with others to illustrate single and multiple inheritance.  Even 
  889. though you do not understand all of the details of these files, 
  890. spend enough time that you are comfortable with the structure and 
  891. the major points of them.
  892.  
  893. We will continue our discussion of encapsulation in the next chapter.
  894.  
  895.  
  896. PROGRAMMING EXERCISES
  897. -----------------------------------------------------------------
  898. 1.  Add a method to CLAS.CPP which will supply the square of the 
  899.     stored value.  Include some code in the main program to read 
  900.     and display the squared values.
  901.     
  902. 2.  Continuing with CLAS.CPP, add a constructor to initialize the 
  903.     stored value to 10 and add a few lines of code to the main 
  904.     program to display the values immediately following the 
  905.     object definition.
  906.  
  907. 3.  Add an output statement to the rectangle constructor of the 
  908.     program named CONSPOLE.CPP and another to the destructor to 
  909.     prove to yourself that they really are called by the system 
  910.     when we said they are.
  911.  
  912. 4.  Write a more comprehensive program to use the date class 
  913.     presented at the end of this chapter.
  914.  
  915. 5.  Write a name class which is somewhat similar to the date 
  916.     class which can store any name in three parts and return the 
  917.     full name in any of several different formats such as the 
  918.     following;
  919.  
  920.       John Paul Doe
  921.       J. P. Doe
  922.       Doe, John Paul
  923.         and any other formats you desire.
  924.  
  925.     If this is carefully planned, it could be useful to you 
  926.     someday.
  927.                                                         Page 5-16
  928.