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

Slides:



Advertisements
Similar presentations
Chapter 11 Separate Compilation and Namespaces. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Separate Compilation.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 11 Separate Compilation and Namespaces Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12A Separate Compilation and Namespaces For classes this time.
CS-212 Intro to C++. Abstract Data Type Abstraction of a real world object as a mathematical entity Implementation independent model of the entity Emphasis.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation Namespaces Simple Make Files (Ignore all class references.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
1 Lab Session-XII CSIT121 Fall 2000 b Namespaces b Will This Program Compile ? b Master of Deceit b Lab Exercise 12-A b First Taste of Classes b Lab Exercise.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
1 Lab Session-XIV CSIT121 Spring 2002 b Namespaces b First Class Travel b Lab Exercise 14 (Demo) b Lab Exercise b Practice Problem.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Guide To UNIX Using Linux Third Edition
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
1 Friends and Namespace COSC 1567 C++ Programming Lecture 6.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
Separate Compilation. A key concept in programming  Two kinds of languages, compilation (C, Pascal, …) and interpretation (Lisp, …, Matlab, Phython,
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
The Structure of a C++ Program. Outline 1. Separate Compilation 2. The # Preprocessor 3. Declarations and Definitions 4. Organizing Decls & Defs into.
Concordia University Department of Computer Science and Software Engineering COMP345 Advanced Program Design with C++ Lecture 1: C++ basics 1.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
CHAPTER 13 CLASSES AND DATA ABSTRACTION. In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
L function n predefined, programmer-defined l arguments, (formal) parameters l return value l function call, function invocation l function definition.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 1:
1 A simple C++ program // ======================================================= // File:helloworld.cpp // Author:Vana Doufexi // Date:1/4/2006 // Description:Displays.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
1 Class Features and Design Issues COSC 1567 C++ Programming Lecture 5.
1 Problem Solving with C++ The Object of Programming Walter Savitch Chapter 8 Tools for Defining ADTs Slides by David B. Teague, Western Carolina University,
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Computing and Statistical Data Analysis Lecture 6 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Introduction to classes and objects:
1 CSC 222: Computer Programming II Spring 2004  classes and objects  abstract data types, classes and objects  using existing classes, #include, member.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Chapter 9 Separate Compilation and Namespaces. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Separate Compilation (9.1)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation and Namespaces.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Separate Compilation and Namespaces.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Separating Class Specification tMyn1 Separating Class Specification from Implementation Usually class declarations are stored in their own header files.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Object Access m1.write(44); m2.write(m2.read() +1); std::cout
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Chapter 12 Classes and Abstraction
Introduction to C++ (Extensions to C)
Chapter 1.2 Introduction to C++ Programming
What Is? function predefined, programmer-defined
Chapter 1.2 Introduction to C++ Programming
ANNOUNCEMENT The missed lecture will be made up this Monday evening in the Tech PC classroom (MG51). A tentative time interval is 6:30-8:00. The exact.
Advanced Program Design with C++
Andy Wang Object Oriented Programming in C++ COP 3330
Separate Compilation and Namespaces
Chapter Structured Types, Data Abstraction and Classes
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Separate Compilation and Namespaces
Operator Overloading.
What Is? function predefined, programmer-defined
Class rational part2.
Chapter 1 c++ structure C++ Input / Output
Presentation transcript:

Chapter 11 Separate Compilation and Namespaces

Learning Objectives Separate Compilation –Encapsulation reviewed –Header and implementation files Namespaces –using directives –Qualifying names –Unnamed namespaces –Hiding helping functions –Nested 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

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

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

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

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

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

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.

Display 11.1 Interface File for the DigitalTime Class 2/2 15.private: int hour; 18. int minute; 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: //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 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.};

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

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

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

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

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

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

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"

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

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

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

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

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

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

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

Self-Test Exercise 5 Suppose you want to change the implementation of the class DigitalTime given in Displays 11.1 and 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 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.

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

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

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

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

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

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

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

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

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!

Self-Test Exercises 6,7 6.Consider the program shown in Display 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);

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;

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

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

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

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.

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

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

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

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

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

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

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

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)

Self-Test Exercise 10 Would the program in Display 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;

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

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

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

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