chapter 11 separate compilation and namespaces. learning objectives separate compilation...

53
Chapter 11 Separate Compilation and Namespaces

Upload: harvey-houston

Post on 14-Dec-2015

237 views

Category:

Documents


1 download

TRANSCRIPT

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

Chapter 11

Separate Compilation and Namespaces

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

Learning Objectives

• Separate Compilation– Encapsulation reviewed– Header and implementation files

• Namespaces– using directives– Qualifying names– Unnamed namespaces– Hiding helping functions– Nested namespaces

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

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

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

Class Separation

• Class Independence– Separate class definition/specification

• Called "interface"

– Separate class implementation– Place in two files

• If implementation changes only thatfile need be changed

• Class specification need not change• "User" programs need not change

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

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

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

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 tousers of class

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

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

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

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., <iostream>• < > indicate predefined library header file• Find it in library directory

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

Display 11.1 Interface File for the DigitalTime Class 1/2

1. #include <iostream>2. using namespace std;

3. class DigitalTime4. {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.

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

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. };

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

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 containexecutable code– e.g., Function definitions, including main()

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

Display 11.2 Implementation File 1/5

1. #include <iostream>2. #include <cctype>3. #include <cstdlib>4. using namespace std;5. #include "dtime.h"

6. //Uses iostream and cstdlib:7. DigitalTime::DigitalTime(int theHour, int theMinute)8. {9. if (theHour < 0 || theHour > 24 || theMinute < 0 || theMinute > 59)10. {11. cout << "Illegal argument to DigitalTime constructor.";12. exit(1);13. }14. else15. {16. hour = theHour;17. minute = theMinute;18. }

19. if (hour == 24)20. hour = 0; //standardize midnight as 0:0021. }

22. DigitalTime::DigitalTime( )23. {24. hour = 0;25. minute = 0;26. }

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

Display 11.2 Implementation File 2/5

27. int DigitalTime::getHour( ) const28. {29. return hour;30. }

31. int DigitalTime::getMinute( ) const32. {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. }

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

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. }

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

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 < 0 || 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. }

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

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 < 0 || theHour > 23 )116. {117. cout << "Error illegal input to readHour\n";118. exit(1);119. }120. }

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

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"

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

Display 11.3 Application File Using DigitalTime Class

//This is the application file: timedemo.cpp which demonstrates use of DigitalTime.1. #include <iostream>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 DIALOGUEYou 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:25You entered 11:1515 minutes later the time will be 11:302 hours and 15 minutes after that the time will be 13:45

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

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

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

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 definitionsof header file

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

Display 11.4 Avoiding Multiple Definitions of a Class

• #ifndef DTIME_H• #define DTIME_H

• #include <iostream>• using namespace std;

• class DigitalTime• {

<The definition of the class DigitalTime is the same as in Display 11.1>• };

• #endif //DTIME_H

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

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

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

Self-Test Exercise 1Suppose 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

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

Self-Test Exercises 2,3,42. 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:

2. The interface file for a class,

3. The implementation file for a class

4. The application file that use the class

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

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.

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

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

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

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

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

Namespace std

• We’ve used namespace std• Contains all names defined in many standard

library files• Example:

#include <iostream>– Places all name definitions (cin, cout, etc.)

into std namespace– Program doesn’t know names– Must specify this namespace for program

to access names

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

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

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

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

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

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

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

Creating a Namespace

• Use namespace grouping:namespace Name_Space_Name{

Some_Code}

• Places all names defined in Some_Codeinto namespace Name_Space_Name

• Can then be made available:using namespace Name_Space_Name

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

Creating a Namespace Example

• Function declaration:namespace Space1{

void greeting();}

• Function definition:namespace Space1{

void greeting(){

cout << "Hello from namespace Space1.\n";}

}

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

Display 11.5 Namespace Demonstration

1. #include <iostream>2. using namespace std;

3. namespace Space14. {5. void greeting( );6. }

7. namespace Space28. {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 Space126. {27. void greeting( )28. {29. cout << "Hello from namespace Space1.\

n";30. }31. }

32. namespace Space233. {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!

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

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);

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

using Declarations

• Can specify individual names from namespace

• Consider:Namespaces NS1, NS2 existEach have functions fun1(), fun2 ()– Declaration syntax:

using Name_Space::One_Name;– Specify which name from each:

using NS1::fun1;using NS2::fun2;

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

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

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

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

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

Self-Test Exercise 8What is the output produced by the following program?

1. #include <iostream>2. using namespace std;

3. namespace Hello4. {5. void message();6. }

7. namespace GoodBye8. {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 Hello28. {29. void message()30. { 31. cout << “Hello.\n”;32. } 33. }

34. namespace GoodBye35. {36. void message()37. { 38. cout << “Good-Bye. \n”;39. } 40. }

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

Self-Test Exercise 9Write 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.

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

Naming Namespaces

• Include unique string– Like last name

• Reduces chance of other namespaceswith same name

• Often multiple programmers writenamespaces for same program– Must have distinct names– Without multiple definitions of same name

in same scope• Results in error

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

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

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

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

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

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

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

Display 11.8 Hiding the Helping Functions in a Namespace (Interface file)

1. #ifndef DTIME_H2. #define DTIME_H

3. #include <iostream>4. using std::istream;5. using std::ostream;

6. namespace DTimeSavitch7. {8. class DigitalTime9. {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

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

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

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

Nested Namespaces

• Legal to nest namespacesnamespace S1{

namespace S2{

void sample(){

…}

}//S2• }//S1

• Qualify names twice:– S1::S2::sample();

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

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)

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

Self-Test Exercise 10Would the program in Display 11.10 behave any differently if you

replaced the four using declarations1. 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;

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

Self-Test Exercise 11What is the output produced by the following program?

1. #include <iostream>2. using namespace std;

3. namespace Sally4. {5. void message();6. }

7. namespace8. {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 Sally21. {22. void message()23. { 24. cout << “Hello from Sally.\n”;25. } 26. }

27. namespace28. {29. void message()30. { 31. cout << “Hello from unnamed. \n”;32. } 33. }

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

Self-Test Exercise 12What is the output produced by the following program?

1. #include <iostream>2. using namespace std;

3. namespace Outer4. {5. void message();6. namespace Inner7. {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 Outer21. {22. void message()23. { 24. cout << “Outer.\n”;25. } 26. namespace Inner27. {28. void message()29. {30. cout << “Inner. \n”;31. }32. }33. }

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

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

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

Summary 2

• Namespace definitions are placedinside 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