Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 11 Separate Compilation and Namespaces. Learning Objectives Separate Compilation –Encapsulation reviewed –Header and implementation files Namespaces.

Similar presentations


Presentation on theme: "Chapter 11 Separate Compilation and Namespaces. Learning Objectives Separate Compilation –Encapsulation reviewed –Header and implementation files Namespaces."— Presentation transcript:

1 Chapter 11 Separate Compilation and Namespaces

2 Learning Objectives Separate Compilation –Encapsulation reviewed –Header and implementation files Namespaces –using directives –Qualifying names –Unnamed namespaces –Hiding helping functions –Nested namespaces

3 Separate Compilation Program Parts –Kept in separate files –Compiled separately –Linked together before program runs Class definitions –Separate from "using" programs –Build library of classes Re-used by many different programs Just like predefined libraries

4 Class Separation Class Independence –Separate class definition/specification Called "interface" –Separate class implementation –Place in two files If implementation changes  only that file need be changed Class specification need not change "User" programs need not change

5 Encapsulation Reviewed Encapsulation principle: –Separate how class is used by programmer from details of class’s implementation "Complete" separation –Change to implementation  NO impact on any other programs Basic OOP principle

6 Encapsulation Rules Rules to ensure separation: 1.All member variables should be private 2.Basic class operations should be: Public member functions Friend or ordinary functions Overloaded operators Group class definition and prototypes together Called "interface" for class 3.Make class implementation unavailable to users of class

7 More Class Separation Interface File –Contains class definition with function and operator declarations/prototypes –Users "see" this –Separate compilation unit Implementation File –Contains member function definitions –Separate compilation unit

8 Class Header Files Class interface always in header file –Use.h naming convention Programs that use class will "include" it –#include "myclass.h" –Quotes indicate you wrote header Find it in "your" working directory –Recall library includes, e.g., indicate predefined library header file Find it in library directory

9 Display 11.1 Interface File for the DigitalTime Class 1/2 1.#include 2.using namespace std; 3.class DigitalTime 4.{ 5.public: 6. DigitalTime(int theHour, int theMinute); 7. DigitalTime( ); 8. //Initializes the time value to 0:00 (which is midnight). 9. getHour( ) const; 10. getMinute( ) const; 11. void advance(int minutesAdded); 12. //Changes the time to minutesAdded minutes later. 13. void advance(int hoursAdded, int minutesAdded); 14. //Changes the time to hoursAdded hours plus minutesAdded minutes later.

10 Display 11.1 Interface File for the DigitalTime Class 2/2 15.private: 16. 17. int hour; 18. int minute; 19. 20. static void readHour(int& theHour); 21. //Precondition: Next input in to be read from the keyboard is 22. //a time in notation, like 9:45 or 14:45. 23. //Postcondition: theHour has been set to the hour part of the time. 24. //The colon has been discarded and the next input to be read is the minute. 25. static void readMinute(int& theMinute); 26. //Reads the minute from the keyboard after readHour has read the hour. 27. static int digitToInt(char c); 28. //Precondition: c is one of the digits ??through ?? 29. //Returns the integer for the digit; that is, digitToInt(?? returns 3. 30. friend bool operator ==(const DigitalTime& time1, const DigitalTime& time2); 31. friend istream& operator >>(istream& ins, DigitalTime& theObject); 32. friend ostream& operator <<(ostream& outs, const DigitalTime& theObject); 33.};

11 Class Implementation Files Class implementation in.cpp file –Typically give interface file and implementation file same name myclass.h and myclass.cpp –All class’s member function defined here –Implementation file must #include class’s header file.cpp files in general, typically contain executable code –e.g., Function definitions, including main()

12 Display 11.2 Implementation File 1/5 1.#include 2.#include 3.#include 4.using namespace std; 5.#include "dtime.h" 6.//Uses iostream and cstdlib: 7.DigitalTime::DigitalTime(int theHour, int theMinute) 8.{ 9. if (theHour 24 || theMinute 59) 10. { 11. cout << "Illegal argument to DigitalTime constructor."; 12. exit(1); 13. } 14. else 15. { 16. hour = theHour; 17. minute = theMinute; 18. } 19. if (hour == 24) 20. hour = 0; //standardize midnight as 0:00 21.} 22.DigitalTime::DigitalTime( ) 23.{ 24. hour = 0; 25. minute = 0; 26.}

13 Display 11.2 Implementation File 2/5 27.int DigitalTime::getHour( ) const 28.{ 29. return hour; 30.} 31.int DigitalTime::getMinute( ) const 32.{ 33. return minute; 34.} 35.void DigitalTime::advance(int minutesAdded) 36.{ 37. int grossMinutes = minute + minutesAdded; 38. minute = grossMinutes%60; 39. int hourAdjustment = grossMinutes/60; 40. hour = (hour + hourAdjustment)%24; 41.} 42.void DigitalTime::advance(int hoursAdded, int minutesAdded) 43.{ 44. hour = (hour + hoursAdded)%24; 45. advance(minutesAdded); 46.} 47.bool operator ==(const DigitalTime& time1, const DigitalTime& time2) 48.{ 49. return (time1.hour == time2.hour && time1.minute == time2.minute); 50.}

14 Display 11.2 Implementation File 3/5 51.//Uses iostream: 52.ostream& operator <<(ostream& outs, const DigitalTime& theObject) 53.{ 54. outs << theObject.hour << ':'; 55. if (theObject.minute < 10) 56. outs << '0'; 57. outs << theObject.minute; 58. return outs; 59.} 60.//Uses iostream: 61.istream& operator >>(istream& ins, DigitalTime& theObject) 62.{ 63. DigitalTime::readHour(theObject.hour); 64. DigitalTime::readMinute(theObject.minute); 65. return ins; 66.} 67.int DigitalTime::digitToInt(char c) 68.{ 69. return ( int(c) - int('0') ); 70.}

15 Display 11.2 Implementation File 4/5 71.//Uses iostream, cctype, and cstdlib: 72.void DigitalTime::readMinute(int& theMinute) 73.{ 74. char c1, c2; 75. cin >> c1 >> c2; 76. if (!(isdigit(c1) && isdigit(c2))) 77. { 78. cout << "Error illegal input to readMinute\n"; 79. exit(1); 80. } 81. theMinute = digitToInt(c1)*10 + digitToInt(c2); 82. if (theMinute 59) 83. { 84. cout << "Error illegal input to readMinute\n"; 85. exit(1); 86. } 87.} 88.//Uses iostream, cctype, and cstdlib: 89.void DigitalTime::readHour(int& theHour) 90.{ 91. char c1, c2; 92. cin >> c1 >> c2; 93. if ( !( isdigit(c1) && (isdigit(c2) || c2 == ':' ) ) ) 94. { 95. cout << "Error illegal input to readHour\n"; 96. exit(1); 97. }

16 Display 11.2 Implementation File 5/5 98. if (isdigit(c1) && c2 == ':') 99. { 100. theHour = DigitalTime::digitToInt(c1); 101. } 102. else //(isdigit(c1) && isdigit(c2)) 103. { 104. theHour = DigitalTime::digitToInt(c1)*10 105. + DigitalTime::digitToInt(c2); 106. cin >> c2; //discard ':' 107. if (c2 != ':') 108. { 109. cout << "Error illegal input to readHour\n"; 110. exit(1); 111. } 112. } 113. if (theHour == 24) 114. theHour = 0; //Standardize midnight as 0:00 115. if ( theHour 23 ) 116. { 117. cout << "Error illegal input to readHour\n"; 118. exit(1); 119. } 120.}

17 Class Files Class header file #included by: –Implementation file –Program file Often called "application file" or "driver file" Organization of files is system dependent –Typical IDE has "project" or "workspace" Implementation files "combined" here Header files still "#included"

18 Display 11.3 Application File Using DigitalTime Class //This is the application file: timedemo.cpp which demonstrates use of DigitalTime. 1.#include 2.using namespace std; 3.#include "dtime.h" 4.int main( ) 5.{ 6. DigitalTime clock, oldClock; 7. cout << "You may write midnight as either 0:00 or 24:00,\n" 8. << "but, I will always write it as 0:00.\n" 9. << "Enter the time in 24 hour notation: "; 10. cin >> clock; 11. oldClock = clock; 12. clock.advance(15); 13. if (clock == oldClock) 14. cout << "Something is wrong."; 15. cout << "You entered " << oldClock << endl; 16. cout << "15 minutes later the time will be " 17. << clock << endl; 18. clock.advance(2, 15); 19. cout << "2 hours and 15 minutes after that\n" 20. << "the time will be " 21. << clock << endl; 22. return 0; 23.} SAMPLE DIALOGUE You may write midnight as either 0:00 or 24:00, but I will always write it as 0:00. Enter the time in 24-hour notation: 11:25 You entered 11:15 15 minutes later the time will be 11:30 2 hours and 15 minutes after that the time will be 13:45

19 Multiple Compiles of Header Files Header files –Typically included multiple times e.g., class interface included by class implementation and program file –Must only be compiled once! –No guarantee "which #include" in which file, compiler might see first Use preprocessor –Tell compiler to include header only once

20 Using #ifndef Header file structure: –#ifndef FNAME_H #define FNAME_H … //Contents of header file … #endif FNAME typically name of file for consistency, readability This syntax avoids multiple definitions of header file

21 Display 11.4 Avoiding Multiple Definitions of a Class #ifndef DTIME_H #define DTIME_H #include using namespace std; class DigitalTime { }; #endif //DTIME_H

22 Other Library Files Libraries not just for classes Related functions –Prototypes  header file –Definitions  implementation file Other type definitions –structs, simple typedefs  header file –Constant declarations  header file

23 Self-Test Exercise 1 Suppose that you are defining a class and that you then want to use this class in a program. You want to separate the class and the program parts into separate files as described in this chapter. State whether each of the following should be placed in the interface file, implementation file, or application file. 1.The class definition 2.The declaration for a function that is to serve as a class operation but that is neither a member nor a friend of the class 3.The declaration for an overloaded operator that is to serve as a class operation but that is neither a member nor a friend of the class 4.The declaration for a function is to serve as a class operation but that is neither a member nor a friend of the class 5.The definition for a friend function that is to serve as a class operation 6.The definition for a member function 7.The definition for an overloaded operator that is to serve as a class operation but that is neither a member nor a friend of the class 8.The definition for an overloaded operator that is to serve as a class operation and that is neither a friend of the class 9.The main function of your program

24 Self-Test Exercises 2,3,4 2.Which of the following files has a name that ends in.h: 1.The interface file for a class, 2.The implementation file for a class 3.The application file that use the class 3.When you define a class in separate files, there is an interface file and an implementation file. Which of these files needs to be compiled? 1.Both? 2.Neither? 3.Only one ? If so, which one? 4.Suppose you define a class in separate files and use the class in a program. Now suppose you change the class implementation file. Which of the following files, if any, needs to be recompiled: 1.The interface file for a class, 2.The implementation file for a class 3.The application file that use the class

25 Self-Test Exercise 5 Suppose you want to change the implementation of the class DigitalTime given in Displays 11.1 and 11.2. Specifically, you want to change the way the time is recorded. Instead of using the two private variables hour and minute, you want to use a single (private) int variable, which will be called minutes. In this new implementation the private variable minutes will record the time as the number of minutes since the time 0:00 (that is, since midnight). For example, 1:30 is recorded as 90 minutes, since it is 90 minutes past midnight. Describe how you need to change the interface and implementation files shown in Displays 11.1 and 11.2. You need not write out the files in their entirety; just indicate what items you need to change and how, in a very general way, you would change them.

26 Namespaces Namespace defined: A collection of name definitions –Class definitions –Variable declarations Programs use many classes, functions –Commonly have same names –Namespaces deal with this –Can be "on" or "off" If names might conflict  turn off

27 using Directive using namespace std; –Makes all definitions in std namespace available Why might you NOT want this? –Can make cout, cin have non-standard meaning Perhaps a need to redefine cout, cin –Can redefine any others

28 Namespace std We’ve used namespace std Contains all names defined in many standard library files Example: #include –Places all name definitions (cin, cout, etc.) into std namespace –Program doesn’t know names –Must specify this namespace for program to access names

29 Global Namespace All code goes in some namespace Unless specified  global namespace –No need for using directive –Global namespace always available –Implied "automatic" using directive

30 Multiple Names Multiple namespaces –e.g., global, and std typically used What if name defined in both? –Error –Can still use both namespaces –Must specify which namespace used at what time

31 Specifying Namespaces Given namespaces NS1, NS2 –Both have void function myFunction() defined differently { using namespace NS1; myFunction(); } { using namespace NS2; myFunction(); } –using directive has block-scope

32 Creating a Namespace Use namespace grouping: namespace Name_Space_Name { Some_Code } Places all names defined in Some_Code into namespace Name_Space_Name Can then be made available: using namespace Name_Space_Name

33 Creating a Namespace Example Function declaration: namespace Space1 { void greeting(); } Function definition: namespace Space1 { void greeting() { cout << "Hello from namespace Space1.\n"; } }

34 Display 11.5 Namespace Demonstration 1.#include 2.using namespace std; 3.namespace Space1 4.{ 5. void greeting( ); 6.} 7.namespace Space2 8.{ 9. void greeting( ); 10.} 11.void bigGreeting( ); 12.int main( ) 13.{ 14. { 15. using namespace Space2; 16. greeting( ); 17. } 18. { 19. using namespace Space1; 20. greeting( ); 21. } 22. bigGreeting( ); 23. return 0; 24.} 25.namespace Space1 26.{ 27. void greeting( ) 28. { 29. cout << "Hello from namespace Space1.\n"; 30. } 31.} 32.namespace Space2 33.{ 34. void greeting( ) 35. { 36. cout << "Greetings from namespace Space2.\n"; 37. } 38.} 39.void bigGreeting( ) 40.{ 41. cout << "A Big Global Hello!\n"; 42.} SAMPLE DIALOGUE Greetings from namespace Space2. Hello from namespace Space1 A Big Global Hello!

35 Self-Test Exercises 6,7 6.Consider the program shown in Display 11.5. Could we use the name greeting in place of bigGreeting? 7.In Exercise 6, we saw that you could not add a definition for the following function to the global namespace: void greeting(); Can you add a definition for the following function declaration to the global namespace? void greeting(int howMany);

36 using Declarations Can specify individual names from namespace Consider: Namespaces NS1, NS2 exist Each have functions fun1(), fun2 () –Declaration syntax: using Name_Space::One_Name; –Specify which name from each: using NS1::fun1; using NS2::fun2;

37 using Definitions and Declarations Differences: –using declaration Makes ONE name in namespace available Introduces names so no other uses of name are allowed –using directive Makes ALL names in namespace available Only "potentially" introduces names

38 Qualifying Names Can specify where name comes from –Use "qualifier" and scope-resolution operator –Used if only intend one use (or few) NS1::fun1(); –Specifies that fun() comes from namespace NS1 Especially useful for parameters: int getInput(std::istream inputStream); –Parameter found in istream’s std namespace –Eliminates need for using directive or declaration

39 Self-Test Exercise 8 What is the output produced by the following program? 1.#include 2.using namespace std; 3.namespace Hello 4.{ 5. void message(); 6.} 7.namespace GoodBye 8.{ 9. void message(); 10.} 11.void message(); 12.Int main() 13.{ 14. using GoodBye::message; 15. { 16. using Hello::message; 17. message(); 18. GoodBye::message(); 19. } 20. message(); 21. return 0; 22.} 23.void message() 24.{ 25. cout << “Global message. \n”; 26.} 27.namespace Hello 28.{ 29. void message() 30. { 31. cout << “Hello.\n”; 32. } 33.} 34.namespace GoodBye 35.{ 36. void message() 37. { 38. cout << “Good-Bye. \n”; 39. } 40.}

40 Self-Test Exercise 9 Write the declaration (prototype) for a void function named wow. The function wow has two parameters, the first type speed as defined in the speedway namespace and the second of type speed as defined in the indy500 namespace.

41 Naming Namespaces Include unique string –Like last name Reduces chance of other namespaces with same name Often multiple programmers write namespaces for same program –Must have distinct names –Without  multiple definitions of same name in same scope Results in error

42 Class Namespace Example: Display 11.6 Placing a Class in a Namespace (Header File)

43 Class Namespace Example: Display 11.7 Placing a Class in a Namespace (Implementation File)

44 Unnamed Namespaces Compilation unit defined: –A file, along with all files #included in file Every compilation unit has unnamed namespace –Written same way, but with no name –All names are then local to compilation unit Use unnamed namespace to keep things "local" Scope of unnamed namespace is compilation unit

45 Display 11.8 Hiding the Helping Functions in a Namespace (Interface file) 1.#ifndef DTIME_H 2.#define DTIME_H 3.#include 4.using std::istream; 5.using std::ostream; 6.namespace DTimeSavitch 7.{ 8. class DigitalTime 9. { 10. public: 11. DigitalTime(int theHour, int theMinute); 12. DigitalTime( ); 13. //Initializes the time value to 0:00 (which is midnight). 14. getHour( ) const; 15. getMinute( ) const; 16. void advance(int minutesAdded); 17. //Changes the time to minutesAdded minutes later. 18. void advance(int hoursAdded, int minutesAdded); 19. //Changes the time to hoursAdded hours plus minutesAdded minutes later. 20. friend bool operator ==(const DigitalTime& time1, const DigitalTime& time2); 21. friend istream& operator >>(istream& ins, DigitalTime& theObject); 22. friend ostream& operator <<(ostream& outs, const DigitalTime& theObject); 23. private: 24. int hour; 25. int minute; 26. }; 27.} //DTimeSavitch 28.#endif //DTIME_H

46 Global vs. Unnamed Namespaces Not same Global namespace: –No namespace grouping at all –Global scope Unnamed namespace: –Has namespace grouping, just no name –Local scope

47 Nested Namespaces Legal to nest namespaces namespace S1 { namespace S2 { void sample() { … } }//S2 }//S1 Qualify names twice: –S1::S2::sample();

48 Hiding Helping Functions Recall helping function: –Low-level utility –Not for public use Two ways to hide: –Make private member function If function naturally takes calling object –Place in class implementation’s unnamed namespace! If function needs no calling object Makes cleaner code (no qualifiers)

49 Self-Test Exercise 10 Would the program in Display 11.10 behave any differently if you replaced the four using declarations 1.using std::cout; 2.using std::cin; 3.using std::endl; 4.using DTimeSavitch::DigitalTime; with the following two using directives? 1.using namespace std; 2.using namespace DTimeSavitch;

50 Self-Test Exercise 11 What is the output produced by the following program? 1.#include 2.using namespace std; 3.namespace Sally 4.{ 5. void message(); 6.} 7.namespace 8.{ 9. void message(); 10.} 11.Int main() 12.{ 13. { 14. message(); 15. using Sally::message; 16. message(); 17. } 18. message(); 19. 20. return 0; 21.} 20.namespace Sally 21.{ 22. void message() 23. { 24. cout << “Hello from Sally.\n”; 25. } 26.} 27.namespace 28.{ 29. void message() 30. { 31. cout << “Hello from unnamed. \n”; 32. } 33.}

51 Self-Test Exercise 12 What is the output produced by the following program? 1.#include 2.using namespace std; 3.namespace Outer 4.{ 5. void message(); 6. namespace Inner 7. { 8. void message(); 9. } 10.} 11.Int main() 12.{ 13. Outer::message(); 14. Outer::Inner::message(); 15. using namespace Outer; 16. Inner::message(); 17. 18. return 0; 19.} 20.namespace Outer 21.{ 22. void message() 23. { 24. cout << “Outer.\n”; 25. } 26. namespace Inner 27. { 28. void message() 29. { 30. cout << “Inner. \n”; 31. } 32. } 33.}

52 Summary 1 Can separate class definition and implementation  separate files –Separate compilation units Namespace is a collection of name definitions Three ways to use name from namespace: –Using directive –Using declaration –Qualifying

53 Summary 2 Namespace definitions are placed inside namespace groupings Unnamed namespace –Used for local name definitions –Scope is compilation unit Global namespace –Items not in a namespace grouping at all –Global scope


Download ppt "Chapter 11 Separate Compilation and Namespaces. Learning Objectives Separate Compilation –Encapsulation reviewed –Header and implementation files Namespaces."

Similar presentations


Ads by Google