View
213
Download
0
Tags:
Embed Size (px)
Citation preview
Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 12AChapter 12ASeparate CompilationSeparate Compilation
and and NamespacesNamespaces
For classes this timeFor classes this time
Reread the former Chapter 12 which discussed Reread the former Chapter 12 which discussed multiple files, separate compilation, and a small multiple files, separate compilation, and a small section on namespaces for programs not using section on namespaces for programs not using classes.classes.
The former Chapter 12 also introduced make The former Chapter 12 also introduced make files which are independent of class files which are independent of class considerations.considerations.
This version of Chapter 12, namely Chapter This version of Chapter 12, namely Chapter 12A, discusses these issues when classes are 12A, discusses these issues when classes are used.used.
Slide 12- 3
OverviewOverview
12.1 Separate Compilation12.1 Separate Compilation
12.2 Namespaces12.2 Namespaces
Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
12.112.1Separate CompilationSeparate Compilation
Slide 12- 5
Separate CompilationSeparate Compilation
C++ allows you to divide a program into partsC++ allows you to divide a program into parts Each part can be stored in a separate fileEach part can be stored in a separate file Each part can be compiled separatelyEach part can be compiled separately A class definition can be stored separately A class definition can be stored separately
from a program.from a program.
This allows you to use the class in multiple This allows you to use the class in multiple programs - a desirable concept as a class programs - a desirable concept as a class essentially defines a new data typeessentially defines a new data type
Slide 12- 6
ADT ReviewADT ReviewAn Abstract Data Type (ADT) is a class defined to An Abstract Data Type (ADT) is a class defined to separate the interface and the implementationseparate the interface and the implementation All member variables are privateAll member variables are private The class definition along with the function and The class definition along with the function and
operator declarations are grouped together as the operator declarations are grouped together as the interface of the ADTinterface of the ADT
Group the implementation of the operations into Group the implementation of the operations into the the implementation of the ADTimplementation of the ADT and make them and make them unavailable to the programmer who is using the unavailable to the programmer who is using the ADT (i.e. the ADT (i.e. the application application programmerprogrammer doesn't doesn't need to see the source code for this.)need to see the source code for this.)
Slide 12- 7
The ADT InterfaceThe ADT Interface
The interface of the ADT includesThe interface of the ADT includes The class definitionThe class definition The declarations of the basic operations The declarations of the basic operations
which can be one of the followingwhich can be one of the following
Public member functions Public member functions
Friend functionsFriend functions
Ordinary functionsOrdinary functions
Overloaded operatorsOverloaded operators The function commentsThe function comments
Slide 12- 8
The ADT ImplementationThe ADT ImplementationThe implementation of the ADT includesThe implementation of the ADT includes The function definitionsThe function definitions
The public member functionsThe public member functions
The private member functionsThe private member functions
Non-member functionsNon-member functions
Private helper functionsPrivate helper functions Overloaded operator definitionsOverloaded operator definitions Member variablesMember variables Other items required by the definitionsOther items required by the definitions
Slide 12- 9
Separate FilesSeparate Files
In C++ the ADT interface and In C++ the ADT interface and implementation should be stored in implementation should be stored in separate filesseparate files The interface file stores the ADT The interface file stores the ADT
interfaceinterface The implementation file stores the ADT The implementation file stores the ADT
implementationimplementation
Slide 12- 10
A Minor CompromiseA Minor CompromiseThe public part of the class definition is part of The public part of the class definition is part of the ADT interfacethe ADT interface
The private part of the class definition is part of The private part of the class definition is part of the ADT implementation the ADT implementation This would hide it from those using the ADTThis would hide it from those using the ADT
C++ does not allow splitting the public andC++ does not allow splitting the public andprivate parts of the class definition across filesprivate parts of the class definition across files The entire class definition is usually in the The entire class definition is usually in the
interface fileinterface file
Slide 12- 11
Case Study:Case Study: DigitalTimeDigitalTime
The interface file of the DigitalTime ADT class The interface file of the DigitalTime ADT class contains the class definitioncontains the class definition The values of the class are:The values of the class are:
Time of day, such as 9:30, in 24 hour Time of day, such as 9:30, in 24 hour notationnotation
The public members are part of the interfaceThe public members are part of the interface The private members are part of the The private members are part of the
implementationimplementation The comments in the file should provide all The comments in the file should provide all
the details needed to use the ADTthe details needed to use the ADT
The DigitalTime ADT interface is stored in a The DigitalTime ADT interface is stored in a file named dtime.hfile named dtime.h As you know, the .h suffix means this is a As you know, the .h suffix means this is a
header fileheader file Interface files are always header filesInterface files are always header files
A program using dtime.h must include it A program using dtime.h must include it using an include directive using an include directive #include "dtime.h #include "dtime.h""
Slide 12- 12
Naming The Interface FileNaming The Interface File
Slide 12- 14
The Implementation FileThe Implementation FileContains the definitions of the ADT Contains the definitions of the ADT functionsfunctionsUsually has the same name as the header Usually has the same name as the header file but a different suffixfile but a different suffix
Since our header file is named Since our header file is named dtime.h, the implementation file is dtime.h, the implementation file is probably would be named dtime.cppprobably would be named dtime.cppSuffix depends on your system Suffix depends on your system (some use .cxx or .CPP)(some use .cxx or .CPP)
The implementation file requires an include The implementation file requires an include
directive to include the interface file:directive to include the interface file:
#include "dtime.h" #include "dtime.h"
Slide 12- 15
#include "dtime.h"#include "dtime.h"
The Application file is the file that contains The Application file is the file that contains the program that uses the ADTthe program that uses the ADT It is also called a It is also called a driver filedriver file Must use an include directive to include Must use an include directive to include
the interface file:the interface file: #include "dtime.h"#include "dtime.h"
Slide 12- 20
The Application FileThe Application File
Slide 12- 22
Running The ProgramRunning The Program
Basic steps required to run a program:Basic steps required to run a program:(Details vary from system to system!)(Details vary from system to system!) Compile the implementation fileCompile the implementation file Compile the application fileCompile the application file Link the files to create an executable Link the files to create an executable
program using a utility called a linkerprogram using a utility called a linker
Linking is often done automaticallyLinking is often done automatically We have already seen how are system We have already seen how are system
handles these.handles these.
Slide 12- 23
Compile dtime.h ?Compile dtime.h ?The interface file is not compiled separatelyThe interface file is not compiled separately The preprocessor replaces any occurrence of The preprocessor replaces any occurrence of
#include "dtime.h" with the text of dtime.h #include "dtime.h" with the text of dtime.h before compiling before compiling
Both the implementation file and the Both the implementation file and the application file contain #include "dtime.h"application file contain #include "dtime.h"
The text of dtime.h is seen by the compiler The text of dtime.h is seen by the compiler in each of these filesin each of these files
Thus, do not compile dtime.h separatelyThus, do not compile dtime.h separately
Slide 12- 24
Why Three Files?Why Three Files?Using separate files permitsUsing separate files permits The ADT to be used in other programs The ADT to be used in other programs
without rewriting the definition of the class for without rewriting the definition of the class for eacheach
The implementation file can be compiled only The implementation file can be compiled only once even if multiple programs use the ADTonce even if multiple programs use the ADT
Changing the implementation file does not Changing the implementation file does not require changing the program using the ADTrequire changing the program using the ADT
Slide 12- 25
Reusable ComponentsReusable ComponentsAn ADT coded in separate files can be used An ADT coded in separate files can be used over and overover and overThe reusability of such an ADT class The reusability of such an ADT class Saves effort since it does not need to be Saves effort since it does not need to be
RedesignedRedesignedRecodedRecodedRetestedRetested
Is likely to result in more reliable componentsIs likely to result in more reliable components
Slide 12- 26
Multiple ClassesMultiple ClassesA program may use several classesA program may use several classes Each could be stored in its own interface and Each could be stored in its own interface and
implementation filesimplementation files
Some files can "include" other files, that include Some files can "include" other files, that include still othersstill others
It is possible that the same interface file could be It is possible that the same interface file could be included in multiple filesincluded in multiple files
C++ does not allow multiple declarations of a classC++ does not allow multiple declarations of a class The #ifndef directive can be used to prevent The #ifndef directive can be used to prevent
multiple declarations of a classmultiple declarations of a class
Slide 12- 27
Recall #ifndefRecall #ifndefTo prevent multiple declarations of a class,To prevent multiple declarations of a class,we can use these directives:we can use these directives: #define DTIME_H #define DTIME_H
adds DTIME_H to a list indicating DTIME_H adds DTIME_H to a list indicating DTIME_H has been seenhas been seen
#ifndef DTIME_H #ifndef DTIME_H checks to see if DTIME_H has been defined checks to see if DTIME_H has been defined
#endif#endifIf DTIME_H has been defined, skip to #endifIf DTIME_H has been defined, skip to #endif
DTIME_H is the normal convention for DTIME_H is the normal convention for creating an identifier to use with ifndefcreating an identifier to use with ifndef It is the file name in all capsIt is the file name in all caps Use ' _ ' instead of ' . 'Use ' _ ' instead of ' . '
You may use any other identifier, but will You may use any other identifier, but will make your code more difficult to readmake your code more difficult to read
Slide 12- 28
Why DTIME_H?Why DTIME_H?
Slide 12- 30
Defining LibrariesDefining LibrariesYou can create your own libraries of functionsYou can create your own libraries of functions You do not have to define a class to use You do not have to define a class to use
separate filesseparate files If you have a collection of functions…If you have a collection of functions…
Declare them in a header file with their Declare them in a header file with their commentscomments
Define them in an implementation fileDefine them in an implementation file
Use the library files just as you use your Use the library files just as you use your class interface and implementation filesclass interface and implementation files
Slide 12- 31
Section 12.1 ConclusionSection 12.1 ConclusionCan youCan you Determine which belongs to the interface, Determine which belongs to the interface,
implementation or application files?implementation or application files?
Class definitionClass definition
Declaration of a non-member function used Declaration of a non-member function used as an operation of the ADTas an operation of the ADT
Definition of a member functionDefinition of a member function
The main part of the programThe main part of the program Describe the difference between a C++ class Describe the difference between a C++ class
and an ADT?and an ADT?
Slide 12- 33
NamespacesNamespacesA A namespacenamespace is a collection of name definitions, is a collection of name definitions, such as class definitions and variable such as class definitions and variable declarationsdeclarations If a program uses classes and functions If a program uses classes and functions
written by written by different programmers, it may be that the different programmers, it may be that the same namesame nameis used for different thingsis used for different things
Namespaces help us deal with this problemNamespaces help us deal with this problem
Slide 12- 34
The Using DirectiveThe Using Directive#include <iostream> places names such as cin#include <iostream> places names such as cinand cout in the std namespaceand cout in the std namespace
The program does not know about names in theThe program does not know about names in thestd namespace until you addstd namespace until you add using namespace std; using namespace std;
(if you do not use the std namespace, you can(if you do not use the std namespace, you can define cin and cout to behave differently) define cin and cout to behave differently)
Slide 12- 35
The Global NamespaceThe Global Namespace
Code you write is in a namespaceCode you write is in a namespace
it is in the it is in the global namespaceglobal namespace unless you unless you specify a namespacespecify a namespace
The global namespace does not require The global namespace does not require the using directivethe using directive
Slide 12- 36
{ using namespace ns1; my_function( );}
{ using namespace ns2; my_function( );}
Name ConflictsName Conflicts: If the same name is used in two namespaces: If the same name is used in two namespaces The namespaces cannot be used at the same The namespaces cannot be used at the same
timetime Example: If my_function is defined in Example: If my_function is defined in
namespaces ns1 and ns2, the two versions of namespaces ns1 and ns2, the two versions of
my_function could be used in one program my_function could be used in one program by using local using directives this wayby using local using directives this way
Slide 12- 37
Scope Rules For usingScope Rules For using
A block is a list of statements enclosed in { }sA block is a list of statements enclosed in { }s
The scope of a using directive is the block in The scope of a using directive is the block in which it appearswhich it appears
A using directive placed at the beginning of a A using directive placed at the beginning of a file, outside any block, applies to the entire filefile, outside any block, applies to the entire file
Slide 12- 38
Creating a NamespaceCreating a Namespace
To place code in a namespaceTo place code in a namespace Use a namespace groupingUse a namespace grouping
namespace Name_Space_Namenamespace Name_Space_Name { { Some_Code Some_Code } }
To use the namespace createdTo use the namespace created Use the appropriate using directiveUse the appropriate using directive
using namespace Name_Space_Name;using namespace Name_Space_Name;
Slide 12- 39
Namespaces:Namespaces:Declaring a FunctionDeclaring a Function
To add a function to a namespaceTo add a function to a namespace Declare the function in a namespace Declare the function in a namespace
groupinggroupingnamespace savitch1namespace savitch1{{
void greeting( );void greeting( );}}
Slide 12- 40
Namespaces: Defining a FunctionNamespaces: Defining a Function
To define a function declared in a namespaceTo define a function declared in a namespace Define the function in a namespace groupingDefine the function in a namespace grouping
namespace savitch1 namespace savitch1 { { void greeting( ) void greeting( ) { {cout << "Hello from namespace savitch1.\n";cout << "Hello from namespace savitch1.\n"; } } } }
To use a function defined in a namespaceTo use a function defined in a namespace
Include the using directive in the program where Include the using directive in the program where the namespace is to be usedthe namespace is to be used
Call the function as the function would normallyCall the function as the function would normallybe calledbe called int main( ) int main( ) { { { {
using namespace using namespace savitch1;savitch1; greeting( ); greeting( ); } }
Slide 12- 41
Using directive's scope
Namespaces: Using a FunctionNamespaces: Using a Function
Slide 12- 44
namespace ns1{ fun1( ); my_function( ); }
namespace ns2{ fun2( ); my_function( );}
A Namespace ProblemA Namespace ProblemSuppose you have the namespaces below:Suppose you have the namespaces below:
Is there an easier way to use both namespaces Is there an easier way to use both namespaces considering that my_function is in both?considering that my_function is in both?
Slide 12- 45
Qualifying NamesQualifying NamesUsing declarations (not directives) allow us to Using declarations (not directives) allow us to select individual functions to use from select individual functions to use from namespacesnamespaces using ns1::fun1; //makes only fun1 in ns1 using ns1::fun1; //makes only fun1 in ns1
availableavailable
The scope resolution operator identifies a The scope resolution operator identifies a namespace herenamespace here
Means we are using only namespace ns1's Means we are using only namespace ns1's version of fun1version of fun1
If you only want to use the function once, call it If you only want to use the function once, call it
like this like this ns1::fun1( );ns1::fun1( );
Slide 12- 46
Qualifiying Parameter NamesQualifiying Parameter NamesTo qualify the type of a parameter with a To qualify the type of a parameter with a using declarationusing declaration Use the namespace and the type nameUse the namespace and the type name
int get_number (std::istream input_stream) int get_number (std::istream input_stream) … …
istream is the istream defined in namespace istream is the istream defined in namespace stdstd
If istream is the only name needed from If istream is the only name needed from namespace std, then you do not need to usenamespace std, then you do not need to use using namespace std; using namespace std;
Slide 12- 47
Directive/DeclarationDirective/Declaration
A using declaration (using std::cout;) makes A using declaration (using std::cout;) makes only one name available from the namespaceonly one name available from the namespace
A using directive makes all the names in the A using directive makes all the names in the namespace availablenamespace available
A using directive potentially introduces a nameA using directive potentially introduces a name
If ns1 and ns2 both define my_function,If ns1 and ns2 both define my_function, using namespace ns1; using namespace ns1; using namespace ns2; using namespace ns2; is OK, provided my_function is never used! is OK, provided my_function is never used!
Slide 12- 48
A Subtle PointA Subtle Point
A using declaration introduces a name into A using declaration introduces a name into your code: no other use of the name can be your code: no other use of the name can be mademade
using ns1::my_function;using ns1::my_function; using ns2::my_function; using ns2::my_function;
is illegal, even if my_function is never is illegal, even if my_function is never usedused
Slide 12- 49
Unnamed NamespacesUnnamed Namespaces
As we have done helper functions so far, they As we have done helper functions so far, they are not really hidden are not really hidden We would like them to be local to the We would like them to be local to the
implementation file to implement information implementation file to implement information hidinghiding
Unnamed NamespacesUnnamed Namespaces
The unnamed namespace can hide helper The unnamed namespace can hide helper functions functions Names defined in the unnamed Names defined in the unnamed
namespace are local to the compilation namespace are local to the compilation unitunit
A compilation unit is a file (such as an A compilation unit is a file (such as an implementation file) plus any file(s) implementation file) plus any file(s) #included in the file#included in the file
Slide 12- 51
The unnamed groupingThe unnamed groupingEvery compilation unit has an unnamed Every compilation unit has an unnamed namespacenamespace The namespace grouping is written as any other The namespace grouping is written as any other
namespace, but no name is given:namespace, but no name is given:
namespace namespace { { void sample_function( ) void sample_function( ) … … } //unnamed namespace } //unnamed namespace
Names in the unnamed namespaceNames in the unnamed namespace Can be reused outside the compilation unitCan be reused outside the compilation unit Can be used in the compilation unit Can be used in the compilation unit
without a namespace qualifierwithout a namespace qualifier
The rewritten version of the DigitalTimeThe rewritten version of the DigitalTimeinterface is found in the next slide interface is found in the next slide while the implementation file is shown in while the implementation file is shown in
the two slides following the interface file. the two slides following the interface file.
Slide 12- 52
Names In The Names In The unnamed namespaceunnamed namespace
The application file for the DigitalTime ADT The application file for the DigitalTime ADT is shown in the next two slidesis shown in the next two slides
Slide 12- 56
Namespaces Namespaces In An ApplicationIn An Application
Slide 12- 59
Compilation Units OverlapCompilation Units OverlapA header file is #included in two filesA header file is #included in two files It is in two compilation unitsIt is in two compilation units Participates in two unnamed namespaces!Participates in two unnamed namespaces! This is OK as long as each of the This is OK as long as each of the
compilation units makes sense independent compilation units makes sense independent of the otherof the other
A name in the header file's unnamed A name in the header file's unnamed namespace cannot be defined again in the namespace cannot be defined again in the unnamed namespace of the unnamed namespace of the implementation or application fileimplementation or application file
Slide 12- 60
Naming NamespacesNaming Namespaces
To avoid choosing a name for a To avoid choosing a name for a namespace that has already been usednamespace that has already been used Add your last name to the name of the Add your last name to the name of the
namespacenamespace Or, use some other unique stringOr, use some other unique string
Slide 12- 61
Global or Unnamed?Global or Unnamed?
Names in the global namespace have global Names in the global namespace have global scope (all files)scope (all files) They are available without a qualifier to all the They are available without a qualifier to all the
program filesprogram filesNames in the unnamed namespace are local toNames in the unnamed namespace are local toa compilation unita compilation unit They are available without a qualifier within They are available without a qualifier within
the compilation unitthe compilation unit
Slide 12- 62
Section 12.2 ConclusionSection 12.2 Conclusion Can youCan you
Explain the purpose of using interface and Explain the purpose of using interface and implementation files?implementation files?
Describe a namespace?Describe a namespace?
Demonstrate three ways to use the names Demonstrate three ways to use the names in a namespace?in a namespace?