And ObjectsDifferent Sorts of Objects ❏ Base built-in types ❏ “Pure” abstract data types no inheritance ◆ Example: class String, class Vector.... ◆ Inheritance may be used not only for s
Trang 1Advanced C++
Programming
Jean-Paul R IGAULT
Professor, University of Nice Sophia Antipolis
École Supérieure en Sciences Informatiques (ESSI)
930 route des Colles – BP 145
06903 S OPHIA A NTIPOLIS Cedex – France
Email : jpr@essi.fr
Trang 2This document was originally designed as handouts for a third (last) year semester course at ESSI, the Computer Engineering School of the University of Nice Sophia Antipolis The course was first given in the second semester of 1996 It has since been used in continuing education sessions on Advanced C++ in various contexts for several industrial companies.
The present version (3.1) describes a C++ language which complies with the ISO C++ standard (ISO/IEC 14882:1998(E) [13]) Some features described here may not be supported event by
recent C++ compilers Most of them are known to work with 2.95.3, and all of them with
Trang 3Foreword 0-ii
Contents of the Course 0-2
1.Introduction 1-1 Introduction 1-2
Summary 1-2
C++ Characteristics 1-3
C and the Scandinavian School 1-3 Origin and Influences 1-4 Why is C++ a Difficult Language? 1-5
References for this Course 1-6
The C++ Class 2-8
What’s in a Class? .2-8 The “Natural” Generalization of struct 2-9
A Model for Creating Instances 2-11
A Model for Creating Instances: new and delete 2-12
An (Abstract) Data Type 2-16
An (Abstract) Data Type: Redefining Operators 2-17
A Name Space 2-18
A Name Space: Hierarchical in case of Inheritance 2-19
An Encapsulation Unit 2-20
An Encapsulation Unit: Protected Members 2-21
A Reuse Unit through Inheritance 2-22
Trang 4Objects Handling 2-25
Creation, Utilization, and Implementation 2-25
Creating, deleting, and initializing objects 2-26
A Guarantee of Initialization 2-26 Modes for Creating/Deleting Objects 2-27 Constructions/Destructions Order 2-29 Default Construction of Built-in Scalar Types 2-32
Copying Objects 2-33
Copy during Initialization 2-33 Copy during Assignment 2-34 Initialization and Assignment 2-35 Default Copy 2-36 Default Copy: Example 2-37 Deep and Shallow Copy 2-38 Value Semantics 2-39 Preventing Copy of Objects 2-40
3.Advanced Mechanisms and ANSI Extensions 3-1
Summary 3-2
Exceptions 3-3
Motivation 3-3 Basic Mechanism .3-4 Basic Mechanism: Destruction of Automatic Objects 3-5 Basic Mechanism: Reraising (Rethrowing) an Exception 3-6 Basic Mechanism: Uncaught Exceptions .3-7 Exceptions Thrown from within a Constructor 3-8 Throw List of a function 3-11 Organization of Exceptions: catch Resolution 3-12 Organization of Exceptions: Exceptions Hierarchy 3-13 Organization of Exceptions: Class exception 3-15 Organization of Exceptions: Naming Exceptions 3-17 Resource Acquisition is Initialization 3-18 Termination or Resume? 3-20 Exceptions Should Remain Exceptional 3-21
Run Time Type Information (RTTI) 3-22
Motivation 3-22 Operator dynamic_cast 3-24 Class type_info and Operator typeid 3-26 Bad Use of RTTI 3-30 The Zoology of ANSI C++ Casts 3-31
Multiple Inheritance 3-34
Reminders 3-34 Virtual Derivation 3-35 Construction of Virtual Base Classes 3-36
Trang 5General Picture 3-40 Generic Functions: Definition 3-41 Generic Functions: Instantiation 3-42 Generic Functions: Specialization 3-43 Generic Functions: Utilization 3-44 Generic Classes: Definition 3-45 Generic Classes: Definition of Member and Friend Functions 3-46 Generic Classes: Instantiation 3-47 Generic Classes and Class Derivation 3-48 Generic Classes and Friendship 3-49 Generic Classes: Initialization of Static Members 3-50 Member Template and Friends 3-51 Generic Parameters for Classes and Functions 3-53 Generic Classes and Implicit Conversions 3-55 Explicit Instantiation of Generic Functions 3-56 Generic Classes: Total Specialization 3-58 Generic Classes: Partial Specialization 3-59 The Problem of Automatic Template Instantiation 3-61 Automatic Template Instanciation: AT&T C++/Sun CC 3-63 Automatic Template Instantiation: GNU gcc 2.9x 3-65
Miscellaneous ANSI C++ Extensions 3-66
Summary 3-66 Keywords 3-67 Really Miscellaneous 3-68 Scope of Loop Indexes; Variables in Conditions 3-72
Pointers to Class Members 3-73
Motivation 3-73 Utilization of Pointers to Member-Functions 3-75 Pointers to Data Members 3-76 Standard Conversions of Pointers to Members 3-77
Name Packaging (namespace) 3-78
Motivation 3-78 Definition 3-79 Utilization 3-80 Synonyms 3-81 Backwards Compatibility 3-82 Class as a Namespace 3-84
Trang 7Jean-Paul R IGAULT
Professor, University of Nice Sophia Antipolis
École Supérieure en Sciences Informatiques (ESSI)
930 route des Colles – BP 145 – 06903 S OPHIA A NTIPOLIS Cedex – France
Email : jpr@essi.fr
Trang 91 Introduction
Trang 11C and the Scandinavian School
❏ Scandinavian school of object-oriented programming
❏ Hybrid language
◆ Support for procedural (imperative) style
◆ Object-oriented features
❏ Compiled language
❏ Programming safety and run-time efficiency
◆ Maximal static analysis
❏ Upward compatible with (ANSI) C
Trang 13Why is C++ a Difficult Language?
❏ Language mechanisms are intrinsically complex
◆ Need to master the fundamental concepts of
Trang 14References for this Course
[27] The C++ Programming Language – Third Edition
Bjarne S TROUSTRUP – Addison-Wesley, 1997
[6] Advanced C++
Programming Style and Idioms
James O C OPLIEN – Addison Wesley, 1992
[28] The Design and Evolution of C++
Bjarne S TROUSTRUP – Addison-Wesley, 1994
[13] International Standard for Information Systems
Programming Language C++
ISO/IEC 14882:1998(E)
Trang 15Indispensable Books (2)
[14] The C++ Standard Template Library
Nicolai M J OSUTIS – Addison-Wesley, 1999
[25] Effective C++ CD:
85 Specific Ways to Improve your Programs and Design
Scott M EYERS – Addison-Wesley, 2000
[1] Modern C++ Design:
Generic Programming and Design Patterns Applied
Andrei A LEXANDESCU – Addison-Wesley, 2001
[10] Design Patterns
Elements of Reusable Object-Oriented Software
Erich G AMMA et al – Addison-Wesley, 1995
Trang 162 Fundamental Mechanisms in
C++
Trang 18Objects and Types
Trang 19Strong Typing but Implicit Conversions
❏ Standard conversions
◆ Standard conversions as in C and ANSI C
◆ Standard conversions related to inheritance
❏ User-defined conversions
◆ Conversions associated with constructors
Class::Class(Type); // Type → Class
◆ Conversion operators
Class::operator Type() const;
// Class → Type
Trang 20Objects and Types
Strong Typing Makes Overloading Possible (1)
❏ Overloading
◆ Same name for different functions
◆ The functions differ by their parameters
(number and types)
◆ The return value type plays no role
– Distinguishing two functions only from their return value type would break the rule that says that the type of an expression is uniquely determined by its operand types
Trang 21Strong Typing Makes Overloading Possible (2)
❏ Overloading resolution (highly simplified)
1 Search for an exact match (for parameter types)
1.1 Search for an ”exact exact”match
1.2 Search for an exact match by instantiating template functions
1.3 Search for an exact match after promoting char to int
(ANSI C compatibility!)
2 Search for possible standard conversions
3 Search for possible user-defined conversions
❏ The solution must be unique
◆ Impossibility and ambiguity are detected at compile-time
Trang 22Objects And Objects
Different Sorts of Objects
❏ Base (built-in) types
❏ “Pure” abstract data types (no inheritance)
◆ Example: class String, class Vector
◆ Inheritance may be used not only for subtyping
(e.g., code sharing with private inheritance)
❏ Abstract data types with inheritance
◆ Public inheritance (subtyping)
◆ Possibility of dynamic binding (virtual functions, inheritance
polymorphism)
Trang 23What’s in a Class?
❏ A “natural” generalization of struct
❏ A model for creating instances
❏ A type definition (an Abstract Data Type)
❏ The set of its instances (the class extension)
❏ A name space
❏ An encapsulation unit
❏ A reuse unit (through composition and inheritance)
❏ An object (not really in C++!)
Trang 24The C++ Class
The “Natural” Generalization of struct (1)
❏ A class is a like a C++ struct with additions
◆ member-functions
◆ access control
◆ initialization/cleaning up control
◆ inheritance
◆ In fact, a struct in C++ is just a class, but
– all its members are public by default, inheritance level is also public
by default
– thus a C++ struct may have member-functions, constructors,
destructor, operators, private members
Trang 25The “Natural” Generalization of struct (2)
❏ What about C union in C++?
◆ They are defined as a struct where all the members
have the same address
◆ They can have constructors and destructors and
(non static) member-functions
◆ Note that a C++ class with constructors or destructor
cannot be a member of an union
– Since the type of the current member of the union is not memorized, the compiler would not know what to destroy
Trang 26The C++ Class
A Model for Creating Instances
❏ Internal data structure
◆ Underlying C structure
❏ Initialization and cleanup operations
◆ Constructors and destructor
❏ Redefinition and/or overloading of dynamic creation/
deletion
◆ operator new and operator delete
◆ Recall than these operators correspond to only one way of
creating/deleting instances in C++ (out of 4 ways)
Trang 27A Model for Creating Instances: new and delete (1)
❏ Redefining global operators
◆ Prototypes
void *operator new(size_t);
void operator delete(void *);
Trang 28The C++ Class
A Model for Creating Instances: new and delete (2)
❏ Redefining new and delete for a class (hierarchy)
◆ Prototypes
class A { public:
void *operator new(size_t);
void operator delete(void *);
};
◆ These member-functions are static
◆ They are usable only for allocating/deallocating
individual objects of class A (see further)
Trang 29A Model for Creating Instances: new and delete (3)
❏ Overloading global/class operators
◆ Prototypes
void *operator new(size_t, T1, T2, );
◆ Utilization
A *pa = new (t1, t2, ) Ặ );
❏ Operator new with pre-placement (predefined)
#include <new>
void *operator new(size_t, void * );
– The object is allocated at the given ađress (second parameter)
Trang 30The C++ Class
A Model for Creating Instances: new and delete (4)
❏ Allocating/Dealloacating arrays
◆ The previous (either global or class) operators can only be
used for allocating individual objects
◆ For arrays, one must use
void *operator new [] (size_t);
void operator delete [] (void *, size_t );
◆ Usage
A *pa = new A [n] ; delete [] pa;
◆ The array element type must have a default constructor
Trang 31An (Abstract) Data Type
❏ Regard instances as first class citizen
❏ Define the new type according to three viewpoints:
◆ Internal representation of instances
– Underlying C structure
◆ Legal operations on instances
– Member-functions (methods) and friends – Basic operators redefinition
◆ Objects common to all instances of the type
(class static variables and member-functions)
Trang 32The C++ Class
An (Abstract) Data Type: Redefining Operators
❏ No new notation for operators
❏ No modification of precedence or associativity
❏ No modification of the number of operands
❏ No redefinition for built-in types
❏ All operators are redefinable, except:
◆ Preprocessor operators: # ##
◆ ”Compile-time” operators: typeid sizeof ::
◆ The three following operators: .* ?:
– However, note that -> and ->* can be redefined
Trang 33A Name Space
class List {
private:
static int nb_lists; // List::nb_lists
int info;
Cell *next;
};
public:
};
Trang 34The C++ Class
A Name Space: Hierarchical in case of Inheritance
class A { public: int i; int j; int n;};
class B : public A {private: int j;};
Trang 35An Encapsulation Unit
❏ Three levels of access control for members
◆ private: exclusively private to the class
◆ protected: private to the class and its derivatives
◆ public: visible and manipulable within any context
❏ Three levels of derivation : inherited members status
◆ private: protected and public → private
◆ protected: public → protected
◆ public: protected and public remain so
◆ For class the default is private, for struct it is public
Trang 36The C++ Class
An Encapsulation Unit: Protected Members
class A {protected: int prot;};
Trang 37A Reuse Unit through Inheritance
❏ Static reuse mechanism
❏ Reusing the interface or the implementation
◆ Interface reuse (public derivation) should satisfy the
substitutability principle (subtyping)
– B is a subtype of A if any instance of A may be replaced by an instance of B
– The substitutability principle expresses the static semantics of inheritance (subtyping)
◆ Implementation reuse often utilizes private inheritance
Trang 38The C++ Class
A Reuse Unit through Inheritance: virtual functions
class Figure { public:
virtual
double surface() const = 0;
virtual void rotate();
Trang 39A Reuse Unit through Composition
❏ Composing with an instance (aggregation)
◆ Different composites cannot share components
◆ The composite is “responsible” for its components
◆ The lifetimes of the composite and its components are
identical
❏ Composition with a pointer or a reference
◆ Make dynamic typing possible when delegating
◆ Sharing is possible
◆ Objects (component and composite) may be independent
Trang 40Objects Handling
Creation, Utilization, and Implementation
❏ Implementation
◆ Internal details
◆ Their knowledge is not needed for creating/using objects
❏ Utilization (and deletion!)
◆ Either the type of the object is known (static typing)
◆ Or dynamic typing (polymorphism) is used, and knowing
a “super-type” of the object is enough
❏ Creation
◆ The exact type of the object must be known
Trang 41A Guarantee of Initialization
❏ If a class has constructors, one if them will be invoked
each time an instance is created
❏ If the constructor requires parameters they must be
provided when creating objects
❏ Otherwise the class must be constructible by default
– Either it has a default constructor
– Or it has no constructor at all: its base class and all its members
must be constructible by default
❏ There is no guarantee of cleanup (destructor call) for
the objects created by
Trang 42Creating, deleting, and initializing objects
Modes for Creating/Deleting Objects (1)
❏ Static objects (permanent lifetime)
◆ Local or global (possibly external)
❏ Automatic objects (block lifetime)
◆ Always local to a block
Trang 43Modes for Creating/Deleting Objects (2)
❏ All created objects have the guarantee of initialization
(call to one constructor)
❏ All objects have the guarantee of cleanup (call to the
destructor) except dynamically allocated ones
◆ Static objects are destroyed at the end of the program
execution (exit())
◆ Automatic objects are destroyed at the end of their block
of definition
◆ Exception objects are destroyed when they are no longer
needed (end of the clause)