Version 3.1— June 2003
Advanced C++ Programming
Advanced C++ Programming Foreword This 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]). [13]). Some features described here may not be supported event by recent C++ compilers. Most of them are known to work with gcc-2.95.3, and all of them with gcc3.2.x. The original document was in French. Only a (large) part of the course has been translated into English. Needless to say that the order for reading slides is the following:
1
2
Advanced C++ Programming Foreword This 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]). [13]). Some features described here may not be supported event by recent C++ compilers. Most of them are known to work with gcc-2.95.3, and all of them with gcc3.2.x. The original document was in French. Only a (large) part of the course has been translated into English. Needless to say that the order for reading slides is the following:
1
2
Advanced C++ Programming Slides List Foreword
0-ii
Slides List
0-iii
Contents of the Course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .0-2
1.Introduction Introduction
1-1 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
Advanced C++ Programming
Slides list
A Reuse Unit through Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-24 Objects Handling
2-25
Creation, Utilization, and Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-25 Creating, deleting, and initializing objects
A Guarantee of Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modes for Creating/Deleting Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Constructions/Destructions Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Default Construction of Built-in Scalar Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Copying Objects
Copy during Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Copy during Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Initialization and Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Default Copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Default Copy: Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deep and Shallow Copy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Value Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Preventing Copy of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.Advanced Mechanisms and ANSI Extensions
2-26 2-26 2-27 2-29 2-32
2-33 2-33 2-34 2-35 2-36 2-37 2-38 2-39 2-40
3-1
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-2
Advanced C++ Programming
Slides list
Conversions and Virtual Base Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-38 Generic Functions and Classes ( template)
3-40
General 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
Summary
3-66 3-66
Advanced C++ Programming
Slides list
Advanced 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 :
[email protected]
Advanced C++ Programming
Advanced C++ Programming Contents of the Course 1. Introduction 2. Fundamental Mechanisms in C++ 3. Advanced Mechanisms and ANSI Extensions
Advanced C++ Programming
1. Introduction
Advanced C++ Programming
Introduction Summary ❏
C++ characteristics
❏
The object-oriented approach
❏
References
1. Introduction
Advanced C++ Programming
1. Introduction
C++ Characteristics C 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
Advanced C++ Programming
1. Introduction
C++ Characteristics Origin and Influences 60
70
80
Fortran
90 Ada
Algol 60 CPL
Ada 95
Algol 68 BCPL
C
ANSI C C with classes
Simula 67
ML
C++
CLU
C++ ARM
C++ std
Eiffel Objective C Java
Smalltalk
Lisp
CLOS
Advanced C++ Programming
1. Introduction
C++ Characteristics Why is C++ a Difficult Language? ❏
Language mechanisms are intrinsically complex ◆
◆
❏
Need to master the fundamental concepts of programming languages However the language is consistent and has a clear philosophy
Object-orientation is a culture ◆ ◆
Stress on architecture Need to give up centralized and purely functional reflexes and habits
Advanced C++ Programming
1. Introduction
References for this Course Indispensable Books
[27] The C++ Programming Language – Third Edition
Bjarne STROUSTRUP – Addison-Wesley, 1997 [6]
Advanced C++ Programming Style and Idioms
James O. COPLIEN – Addison Wesley, 1992 [28] The Design and Evolution of C++
Bjarne STROUSTRUP – Addison-Wesley, 1994 [13] International Standard for Information Systems Programming Language C++
ISO/IEC 14882:1998(E)
(1)
Advanced C++ Programming
1. Introduction
References for this Course Indispensable Books
[14] The C++ Standard Template Library
Nicolai M. JOSUTIS – Addison-Wesley, 1999 [25] Effective C++ CD: 85 Specific Ways to Improve your Programs and Design
Scott MEYERS – Addison-Wesley, 2000 [1]
Modern C++ Design: Generic Programming and Design Patterns Applied
Andrei ALEXANDESCU – Addison-Wesley, 2001 [10] Design Patterns Elements of Reusable Object-Oriented Software
Erich GAMMA et al. – Addison-Wesley, 1995 (also available as a CD )
(2)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Advanced C++ Programming
Fundamental Mechanisms in C++ Summary ❏
Objects and Types
❏
The C++ class
❏
Objects handling
❏
Creating, deleting, and initializing objects
❏
Copying objects
2. Fundamental Mechanisms in C++
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Objects and Types Strong Typing ❏
Unique type ◆ ◆ ◆ ◆
Symbolic and literal constants Variables Functions Expressions
❏
Type of functions: prototypes (as in ANSI C)
❏
Type of an expression ◆
Can be uniquely determined from the type of its components (operands)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Objects and Types Strong 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
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Objects 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
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Objects and Types Strong Typing Makes Overloading Possible ❏
(2)
Overloading resolution (highly simplified)
1. Sear Search ch for for an ex exact act match match (fo (forr para parame meter ter typ types es)) 1.1. Search Search for an ”exa ”exact ct exact”m exact”match atch 1.2. Search for for an exact exact match by by instantiating template functions functions 1.3. Search Search for an exa exact ct match after promoti promoting ng char to int (ANSI C compatibility!) 2. Sear Search ch for for pos possi sibl blee stand standar ardd con convers versio ions ns 3. Sear Search ch for for possi possibl blee useruser-de defin fined ed con conversi ersion onss ❏
The solution must be unique ◆
Impossibility and ambiguity are detected at compile-time
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Objects... 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 inheritance ◆ ◆
Public inheritance (subtyping) Possibility of dynamic binding (virtual (vir tual functions, functions, inheritance polymorphism)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class What’s in a Class? ❏
A “natural” generalization of struct
❏
A model for creating instances
❏
A type definition (an Abstract Abstract Data Dat a 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++!) ...
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The 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...
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class The “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...
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class A Model for Creating Instances ❏
Internal data structure ◆
❏
Initialization and cleanup operations ◆
❏
Underlying C structure Constructors and destructor
Redefinition and/or overloading of dynamic creation/ deletion ◆ ◆
and operator delete Recall than these operators correspond to only one way of creating/deleting instances in C++ (out of 4 ways) operator new
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class A Model for Creating Instances: ❏
new and delete
Redefining global operators ◆
Prototypes void *operator new(size_t); void operator delete(void *);
◆
Utilization A *pa = new A(...);
◆
Generated code // allocation A *pa = (A *)operator new(sizeof(A)); // initialisation pa-> A::A (...);
(1)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class A Model for Creating Instances: new and delete ❏
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)
(2)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class A 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, ...) A(...);
❏
Operator new with pre-placement (predefined) #include
void *operator new(size_t, void *);
– The object is allocated at the given address (second parameter) – The programmer is responsible for allocating storage
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The 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
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class An (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)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The 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 The three following operators: .
sizeof .*
– However, note that -> and ->* can be redefined
:: ?:
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class A Name Space class List { private: static int nb_lists; enum {N1, N2}; class Cell { int info; Cell *next; ... }; Cell *first; Cell *last; public: ... };
// List::nb_lists // List::N1, List::N2 // List::Cell
// this-> first // this-> last
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The 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;}; class C : public B { private:int k; public: void f(double); }; int i; // global variable void C::f(double n) { k = 0; // C::k n = 3.14;// function parameter j = 2; // B::j, but not accessible here i = 3; // A::i i = ::i;// ::i is the global i }
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class An 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
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class An Encapsulation Unit: Protected Members class A {protected: int prot;}; class B1 : public A {}; class B2 : public A { public: void f(void); }; class C : public B2 {};
A
B1 void B2::f(void) A a; B1 b1; B2 prot = 1; a.prot = 2; b1.prot = 3; b2.prot = 4;
c.prot = 5; }
{ b2; C c;
C
// OK : this->prot // KO : no conversion A → B2 // KO : no conversion B1→ B2 // OK : b2 is a B2 !
// OK : conversion C
B2
→
B2
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class A Reuse Unit through Inheritance ❏
Static reuse mechanism
❏
Reusing Reusing the interface inter face or the t he implementation implementation
Interface reuse (public derivation) should satisfy the substitutability principle (subtyping)
◆
–
B is a subtype of A A if any instance of A A may be replaced by an instance of B
– The subs substit tituta utabil bility ity prin princip ciple le expr express esses es the static static seman semantic ticss of inheritance (subtyping) ◆ Implementation reuse often utilizes private inheritance
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class A Reuse Unit through Inheritance: virtual functions funct ions Figure
class Figure { public:
surface() rotate()
virtual double surface() const = 0; virtual void virtual void rotate(); };
Ellipse
surface()
Rectangle
surface()
class Ellipse : public Figure { public: double surface() const { return PI*a*b; } };
Circle
Square Figure *pf = new Circle(...);
rotate()
double s = pf-> = pf->surface() surface(); ;
Advanced C++ Programming
2. Fundamental Mechanisms in C++
The C++ Class A 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
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Objects Handling Creation, Utilization, and Implementation ❏
Implementation ◆ ◆
❏
Utilization (and deletion!) ◆ ◆
❏
Internal details Their knowledge is not needed for creating/using objects 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
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Creating, deleting, and initializing objects A 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 new
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Creating, deleting, and initializing objects Modes for Creating/Deleting Objects ❏
Static objects (permanent lifetime) ◆
❏
Automatic objects (block lifetime) ◆
❏
❏
Local or global (possibly external) Always local to a block
Dynamic objects ◆
Allocated by new , access through pointers
◆
No automatic deletion
Exception objects ◆
Created by throw
(1)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Creating, deleting, and initializing objects Modes 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 catch clause)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Creating, deleting, and initializing objects Constructions/Destructions Order ❏
Construction order 1. Construction of base classe(s) 2. Construction of class own members 3. Constructor body
❏
Destruction order (inverse order) 1. Destructor body 2. Destruction of class own members 3. Destruction of base classe(s)
(1)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Creating, deleting, and initializing objects Constructions/Destructions Order ❏
Base classes are constructed in the order of the derivation list
❏
Members are constructed in the order of their declaration in the class definition – Attention! DANGER ! class B : public A1, public A2 { private: int *pt; int dim; public: B(int n) : dim(n), A1(n), pt(new int[dim ]) {...} // pt(new int[n]) would be correct! };
(2)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Creating, deleting, and initializing objects Constructions/Destructions Order
(3)
class B {public: B(int = 0); ...};
A class A {private: int p; public: A(int = 0); ... }; class A1 : public A { protected: B b1; public: A1(int i = 0, int j = 1) : b1(i), A(j) {...} ... }; class A2 : public A1 {private: B b2;}; A1 a1(2, 3); A2 a2;
A1
A2
B
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Creating, deleting, and initializing objects Default Construction of Built-in Scalar Types ❏
A default constructor is defined for built-in scalar types – that is for integral types (char, int and all their variations, and pointers) and real types ( float and double)
❏
This default constructor is not called by default!!! int g; // static initialization: g initialized to 0 void f() { int a = int(); int b;
// a initialized to 0 // b not initialized by default!!
int *p1 = new int;
// *p1 not initialized by default!! // *p2 initialized to 0 int *p2 = new int(); // *p2 initialized to 14 int *p3 = new int(14); }
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Copying Objects Copy during Initialization ❏
Copy constructor T::T(const T&)
– ❏
const
is optional
This constructor is invoked each time an object is created as a copy of another object of the same type ◆ ◆
Simple initialization (during definition) Passing parameters to and returning from functions by value
◆
Default copy of classes with no copy constructor(s)
(see later)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Copying Objects Copy during Assignment ❏
Copy assignment operator const T& T::operator=(const T&)
❏
This operator is invoked each time an object is assigned to another object of the same type ◆ ◆
Simple assignment Default copy of classes with no assignment operator (see later)
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Copying Objects Initialization and Assignment ❏
An assignment is not an initialization ◆
◆
◆
❏
There is exactly one initialization throughout the entire life of an object Initialization is always possible (once) whereas assignment may be forbidden (const objects) Assignment must take care of the previous state of the object whereas, for initialization, there is no such thing as a previous state
An assignment trap: ◆
Beware:
x = x;
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Copying Objects Default Copy ❏
If a class has copy constructor(s) and/or assignment operator, these functions are entirely responsible for copying objects
❏
Otherwise, default copy is performed memberwise ◆
◆
◆ ◆
Each member is copied according to its own copy semantics Base class(es) are considered as members during the copy operation The memberwise procedure is applied recursively Built-in types are copied bitwise
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Copying Objects Default Copy: Example class Symbol { private: String _name; Value _val; public: // No copy constructor }; Symbol sy1(...); Symbol sy2 = sy1;
–
Symbol
String Value
sy2._name is initialized from sy1._name, most likely by class
copy constructor – If class Value has a copy constructor, this constructor is used to initialize sy2._val from sy1._val; otherwise the inside of type Value, is examined memberwise... String
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Copying Objects Deep and Shallow Copy ❏
Deep Copy ◆
❏
Shallow copy ◆ ◆ ◆
❏
All components are copied, recursively Necessary when components are shared Demand the redefinition of copy operations If sharing is used, it must be explicitly handled
Memberwise copy looks like deep copy but may be in fact intermediate ◆
Everything depends on member copy semantics
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Copying Objects Value Semantics ❏
A class has value semantics iff ◆ ◆
❏
Copy operations are defined (possibly by default) Everything is as if each instance conveys its own value (lvalue /rvalue as in C)
Value semantics is not incompatible with an implementation using sharing ◆
Example: class String with copy-on-write
Advanced C++ Programming
2. Fundamental Mechanisms in C++
Copying Objects Preventing Copy of Objects ❏
To forbid copying objects for a class, make copy operations (copy constructor and copy assignment operator) private – Of course, this forbids copy only outside the class implementation – A bullet-proof solution is to declare the copy operation but not to implement it: any attempt to copy will lead to a link error class Non_Copiable { private: Non_Copiable(const Non_Copiable&); // No body definition Non_Copiable& operator=(const Non_Copiable&); // No body definition ... };
Advanced C++ Programming
3. Advanced Mechanisms and ANSI Extensions
Advanced C++ Programming
3. Advanced Mechanisms and ANSI Extensions
Advanced Mechanisms and ANSI Extensions Summary ❏
Exceptions
❏
Run Time Type Information (RTTI) and new casts
❏
Multiple inheritance
❏
Generic functions and classes (template)
❏
Miscellaneous ANSI C++ extensions
❏
Pointers to class members
❏
Name packaging (namespace)
Advanced C++ Programming
3. Advanced Mechanisms and ANSI Extensions
Exceptions Motivation ❏
Exceptions are mandatory because of encapsulation
❏
What can be done when an abnormal condition is detected inside a class?
Notify the user Allow her to recover and resume the program at a suitable point Separate normal processing from exceptional one Respect the C++ creation/deletion semantics
◆ ◆
◆ ◆
–
are not sufficient because local variables with destructor must be destroyed properly setjmp/longjmp
Advanced C++ Programming
3. Advanced Mechanisms and ANSI Extensions
Exceptions Basic Mechanism main() {f();} void f() { try { ... g(); } catch (E1) {...}; catch (E2) {...} } void g() { try { ... h(); } catch (E1) {...} } void h() { if (...) throw E1(); else throw E2(); }
– An exception is a temporary object (of any type) – When an exception is raised (throw n) the current function is exited, and the exception is propagated upward, traversing (and exiting) functions in the calling chain – The propagation is stopped by the first try block with a catch for the (type of) the exception – The catch clause is executed; if it does nothing special, control is then transferred after the try block (and all its catch clauses)
Advanced C++ Programming
3. Advanced Mechanisms and ANSI Extensions
Exceptions Basic Mechanism: Destruction of Automatic Objects void f() { try { ... g(); } catch (E1) {...}; } void g() { String s("hello"); h(); ... } void h() { String s1("salut"); ... if (...) throw E1(); }
deletion of s
deletion of s1
– If a function is traversed by a propagated exception, all automatic (local) objects are properly destroyed (i.e., their destructor gets invoked) – Nothing similar happens for dynamically allocated objects (allocated by new ) – Thus it is the programmer’s responsibility to provoke the destruction of dynamically allocated objects (see later)