You are on page 1of 143

Version 3.

1 June 2003

Advanced C++ Programming


Jean-Paul R IGAULT

Professor, University of Nice Sophia Antipolis cole Suprieure en Sciences Informatiques (ESSI) 930 route des Colles BP 145 06903 S OPHIA A NTIPOLIS Cedex France Email : jpr@essi.fr

1996-2003 Jean-Paul R IGAULT

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]). 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 3

2 4

1996-2003 Jean-Paul R IGAULT Version 3.1

II

Advanced C++ Programming


Slides List
Foreword Slides List 0-ii 0-iii

Contents of the Course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .0-2

1.Introduction
Introduction C++ Characteristics

1-1
1-2 1-3

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-2

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

Indispensable Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-6

2.Fundamental Mechanisms in C++

2-1

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-2

Objects and Types

2-3

Strong Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-3 Strong Typing... but Implicit Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-4 Strong Typing Makes Overloading Possible . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-5 Different Sorts of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-7

The C++ Class

2-8

Whats 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 A Reuse Unit through Inheritance: virtual functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-23 1996-2003 Jean-Paul R IGAULT V ERSION 3.1
III

Advanced C++ Programming

Slides list

A Reuse Unit through Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-24

Objects Handling Creating, deleting, and initializing objects


A Guarantee of Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Modes for Creating/Deleting Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Constructions/Destructions Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Default Construction of Built-in Scalar Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2-25 2-26
2-26 2-27 2-29 2-32

Creation, Utilization, and Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-25

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

2-33
2-33 2-34 2-35 2-36 2-37 2-38 2-39 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)


Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Operator dynamic_cast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Class type_info and Operator typeid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Bad Use of RTTI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Zoology of ANSI C++ Casts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3-22
3-22 3-24 3-26 3-30 3-31

Multiple Inheritance

3-34

Reminders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-34 Virtual Derivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-35 Construction of Virtual Base Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-36

1996-2003 Jean-Paul R IGAULT Version 3.1

IV

Advanced C++ Programming

Slides list

Conversions and Virtual Base Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-38

Generic Functions and Classes (template)


General Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Functions: Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Functions: Instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Functions: Specialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Functions: Utilization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Classes: Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Classes: Definition of Member and Friend Functions . . . . . . . . . . . . . . . . . . . Generic Classes: Instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Classes and Class Derivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Classes and Friendship . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Classes: Initialization of Static Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . Member Template and Friends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Parameters for Classes and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Classes and Implicit Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Explicit Instantiation of Generic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Classes: Total Specialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Generic Classes: Partial Specialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Problem of Automatic Template Instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Automatic Template Instanciation: AT&T C++/Sun CC . . . . . . . . . . . . . . . . . . . . . . . . Automatic Template Instantiation: GNU gcc 2.9x . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3-40
3-40 3-41 3-42 3-43 3-44 3-45 3-46 3-47 3-48 3-49 3-50 3-51 3-53 3-55 3-56 3-58 3-59 3-61 3-63 3-65

Miscellaneous ANSI C++ Extensions


Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Really Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Scope of Loop Indexes; Variables in Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3-66
3-66 3-67 3-68 3-72

Pointers to Class Members


Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Utilization of Pointers to Member-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pointers to Data Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Standard Conversions of Pointers to Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3-73
3-73 3-75 3-76 3-77

Name Packaging (namespace)


Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Utilization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Synonyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Backwards Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Class as a Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3-78
3-78 3-79 3-80 3-81 3-82 3-84

References

B-1

1996-2003 Jean-Paul R IGAULT Version 3.1

Advanced C++ Programming

Slides list

1996-2003 Jean-Paul R IGAULT Version 3.1

VI

Advanced C++ Programming


Jean-Paul R IGAULT
Professor, University of Nice Sophia Antipolis cole Suprieure en Sciences Informatiques (ESSI) 930 route des Colles BP 145 06903 S OPHIA A NTIPOLIS Cedex France Email : jpr@essi.fr

1996, 2003 Jean-Paul RIGAULT Version 3.1

0-1

Advanced C++ Programming

Advanced C++ Programming


Contents of the Course
1. Introduction 2. Fundamental Mechanisms in C++ 3. Advanced Mechanisms and ANSI Extensions

1996, 2003 Jean-Paul RIGAULT Version 3.1

0-2

Advanced C++ Programming

1. Introduction

1996, 2003 Jean-Paul RIGAULT Version 3.1

1-1

Advanced C++ Programming

1. Introduction

Introduction
Summary C++ characteristics The object-oriented approach References

1996, 2003 Jean-Paul RIGAULT Version 3.1

1-2

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
1996, 2003 Jean-Paul RIGAULT Version 3.1 1-3

Advanced C++ Programming

1. Introduction

C++ Characteristics
Origin and Influences
60 Fortran Algol 60 CPL Algol 68 BCPL C C with classes Simula 67 ML CLU ANSI C 70 80 Ada 90 Ada 95

C++
Eiffel Objective C

C++ ARM

C++ std

Smalltalk Lisp
1996, 2003 Jean-Paul RIGAULT Version 3.1

Java CLOS
1-4

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
1996, 2003 Jean-Paul RIGAULT Version 3.1 1-5

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

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

1996, 2003 Jean-Paul RIGAULT Version 3.1

1-6

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

[10] Design Patterns Elements of Reusable Object-Oriented Software Erich GAMMA et al. Addison-Wesley, 1995
(also available as a CD )
1996, 2003 Jean-Paul RIGAULT Version 3.1 1-7

Advanced C++ Programming

2. Fundamental Mechanisms in C++

1996, 2003 Jean-Paul RIGAULT Version 3.1

2-1

Advanced C++ Programming

2. Fundamental Mechanisms in C++

Fundamental Mechanisms in C++


Summary Objects and Types The C++ class Objects handling Creating, deleting, and initializing objects Copying objects

1996, 2003 Jean-Paul RIGAULT Version 3.1

2-2

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)
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-3

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
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-4

Advanced C++ Programming

2. Fundamental Mechanisms in C++

Objects and Types


Strong Typing Makes Overloading Possible 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

(1)

1996, 2003 Jean-Paul RIGAULT Version 3.1

2-5

Advanced C++ Programming

2. Fundamental Mechanisms in C++

Objects and Types


Strong Typing Makes Overloading Possible Overloading resolution (highly simplified)
1. Search for an exact match (for parameter types) 1.1. Search for an exact exactmatch 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

(2)

The solution must be unique Impossibility and ambiguity are detected at compile-time
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-6

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 Public inheritance (subtyping) Possibility of dynamic binding (virtual functions, inheritance polymorphism)
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-7

Advanced C++ Programming

2. Fundamental Mechanisms in C++

The C++ Class


Whats 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++!) ...
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-8

Advanced C++ Programming

2. Fundamental Mechanisms in C++

The C++ Class


The Natural Generalization of struct 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...
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-9

(1)

Advanced C++ Programming

2. Fundamental Mechanisms in C++

The C++ Class


The Natural Generalization of struct 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...
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-10

(2)

Advanced C++ Programming

2. Fundamental Mechanisms in C++

The 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)
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-11

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

(1)

Utilization
A *pa = new A(...);

Generated code
// allocation A *pa = (A *)operator new(sizeof(A)); // initialisation pa->A::A(...);
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-12

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

(2)

These member-functions are static They are usable only for allocating/deallocating individual objects of class A (see further)
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-13

Advanced C++ Programming

2. Fundamental Mechanisms in C++

The C++ Class


A Model for Creating Instances: new and delete Overloading global/class operators Prototypes
void *operator new(size_t, T1, T2, ...);

(3)

Utilization
A *pa = new (t1, t2, ...) A(...);

Operator new with pre-placement (predefined)


#include <new> void *operator new(size_t, void *); The object is allocated at the given address (second parameter) The programmer is responsible for allocating storage
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-14

Advanced C++ Programming

2. Fundamental Mechanisms in C++

The C++ Class


A Model for Creating Instances: new and delete 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);

(4)

Usage
A *pa = new A[n]; delete[] pa;

The array element type must have a default constructor


1996, 2003 Jean-Paul RIGAULT Version 3.1 2-15

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)
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-16

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 sizeof :: The three following operators: . .* ?:
However, note that -> and ->* can be redefined
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-17

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: ... };
1996, 2003 Jean-Paul RIGAULT Version 3.1

// List::nb_lists // List::N1, List::N2 // List::Cell

// this->first // this->last

2-18

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 }
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-19

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
2-20

1996, 2003 Jean-Paul RIGAULT Version 3.1

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 B2 C

void B2::f(void) A a; B1 b1; B2 prot = 1; a.prot = 2; b1.prot = 3; b2.prot = 4; c.prot = 5; }


1996, 2003 Jean-Paul RIGAULT Version 3.1

{ b2; C // OK // KO // KO // OK // OK

c; : this->prot : no conversion A B2 : no conversion B1 B2 : b2 is a B2 ! : conversion C B2

2-21

Advanced C++ Programming

2. Fundamental Mechanisms in C++

The C++ Class


A 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


1996, 2003 Jean-Paul RIGAULT Version 3.1 2-22

Advanced C++ Programming

2. Fundamental Mechanisms in C++

The C++ Class


A Reuse Unit through Inheritance: virtual functions
Figure surface() rotate() Ellipse surface() Rectangle surface()
class Figure { public: virtual double surface() const = 0; virtual void rotate(); }; class Ellipse : public Figure { public: double surface() const { return PI*a*b; } };

Circle rotate()
1996, 2003 Jean-Paul RIGAULT Version 3.1

Square
Figure *pf = new Circle(...); double s = pf->surface();

2-23

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
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-24

Advanced C++ Programming

2. Fundamental Mechanisms in C++

Objects 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
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-25

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
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-26

Advanced C++ Programming

2. Fundamental Mechanisms in C++

Creating, deleting, and initializing objects


Modes for Creating/Deleting Objects Static objects (permanent lifetime) Local or global (possibly external) Automatic objects (block lifetime) Always local to a block Dynamic objects Allocated by new, access through pointers No automatic deletion Exception objects Created by throw
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-27

(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)
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-28

Advanced C++ Programming

2. Fundamental Mechanisms in C++

Creating, deleting, and initializing objects


Constructions/Destructions Order Construction order
1. 2. 3. 1. 2. 3. Construction of base classe(s) Construction of class own members Constructor body Destructor body Destruction of class own members Destruction of base classe(s)

(1)

Destruction order (inverse order)

1996, 2003 Jean-Paul RIGAULT Version 3.1

2-29

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! };
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-30

(2)

Advanced C++ Programming

2. Fundamental Mechanisms in C++

Creating, deleting, and initializing objects


Constructions/Destructions Order
class B {public: B(int = 0); ...};

(3)

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;
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-31

A1

A2

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(); // a initialized to 0 int b; // b not initialized by default!! int *p1 = new int; // *p1 not initialized by default!! int *p2 = new int(); // *p2 initialized to 0 int *p3 = new int(14); // *p2 initialized to 14 }
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-32

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)
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-33

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)

1996, 2003 Jean-Paul RIGAULT Version 3.1

2-34

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;
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-35

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
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-36

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 String 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...
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-37

Advanced C++ Programming

2. Fundamental Mechanisms in C++

Copying Objects
Deep and Shallow Copy Deep Copy All components are copied, recursively Shallow copy 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
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-38

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

1996, 2003 Jean-Paul RIGAULT Version 3.1

2-39

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 ... };
1996, 2003 Jean-Paul RIGAULT Version 3.1 2-40

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-1

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)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-2

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
setjmp/longjmp are not sufficient because local variables with destructor must be destroyed properly
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-3

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(); }
1996, 2002 Jean-Paul Rigault Version 3.1

An exception is a temporary object (of any type) When an exception is raised (thrown) 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)
3-4

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(); }
1996, 2002 Jean-Paul Rigault Version 3.1

If a function is traversed by a propagated exception, all automatic (local) objects are properly destroyed (i.e., their destructor gets invoked)
deletion of s

Nothing similar happens for dynamically allocated objects (allocated by new) Thus it is the programmers responsibility to provoke the destruction of dynamically allocated objects (see later)
3-5

deletion of s1

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Basic Mechanism: Reraising (Rethrowing) an Exception
main() {f();} void f() { try { ... g(); } catch (E1) {...}; } void g() { try { ... h(); } catch (E1) {...; throw;} } void h() { if (...) throw E1(); }

In a catch clause, using throw without parameter simply repropagates the current exception upwards

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-6

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Basic Mechanism: Uncaught Exceptions If no try block in the calling chain has a catch clause for the current exception, the standard function terminate() is called By default, terminate() simply calls abort() But the user may provide her own version

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-7

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Exceptions Thrown from within a Constructor (1)

All members fully constructed before the exception is thrown are deleted The destructors of fully constructed components are correctly called Partially constructed sub-objects are not destructed It is indispensable to understand clearly in which order constructions/deletions are performed It is not a good idea to throw an exception from within a destructor!
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-8

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Exceptions Thrown from within a Constructor
class A1 { String id; public: A1(const String& s) : id(s) {} }; class A2 { int val; public: A2(int v) {if (v==0) throw Invalid();} }; class B : public A1, public A2 { String name; public: B(const String& s, int v) : A1(s), A2(v) {name = s; throw Exception_B();} };

(2)

What happens when constructing a B: If v = 0? If v 0?


1996, 2003 Jean-Paul RIGAULT Version 3.1 3-9

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Exceptions Thrown from within a Constructor Function try block
void f() try { function-body } catch (E1) { ... } catch (E2) { ... } ...

(3)

Particularly useful for constructors


void A::A() try : initialization-list {
constructor-body

} catch (E1) { ... } ...


1996, 2003 Jean-Paul RIGAULT Version 3.1 3-10

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Throw List of a function It is possible to specify the list of exceptions that a (member or regular) function may throw
void f() throw (E1, E2); void g() throw (); // no exception void h(); // any exception

C++ only requires a dynamic check Static checking is possible but delicate If an exception forbidden by the throw list is thrown, unexpected() is called (and by default abort())
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-11

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Organization of Exceptions: catch Resolution For a same try block, catch clauses are scanned from top to bottom Type conformance must be exact, except that standard conversions related to inheritance (only) are authorized The temporary object created by throw may be retrieved in catch, by value but also by reference
catch (Stack::exception& e) {...} Above, dynamic typing may be honored for e

The form catch (...) captures all exceptions


1996, 2003 Jean-Paul RIGAULT Version 3.1 3-12

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Organization of Exceptions: Exceptions Hierarchy
exception

(1)

system_err

arithmetic_err

IO_err

zero_divide

overflow

underflow

file_err

network_err

Class exception is not indispensible However it is defined in the standard library


3-13

network_file_err
1996, 2003 Jean-Paul RIGAULT Version 3.1

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Organization of Exceptions: Exceptions Hierarchy (2)

try { ... } catch (overflow& ov) {...} catch (arithmetic_err& e) {cout << e.what();} catch (file_err) {...} catch (IO_err) {...} catch (...) {cout << "unexpected exception";} Be careful with catch order!

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-14

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Organization of Exceptions: Class exception Defined in the ANSI standard
class exception { public: exception() throw (); exception(const exception&) throw (); exception& operator=(const exception&) throw (); virtual ~exception() throw (); virtual const char *what() const throw (); };

(1)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-15

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Organization of Exceptions: Class exception (2)

exception

logic_err

runtime_err

domain_error

invalid_argument out_of_range

length_error

overflow_error

range_error

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-16

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Organization of Exceptions: Naming Exceptions
class Stack { public: class All : public My_Lib_Except {...}; class Full : public All {...}; class Empty : public All {...}; ... }; try { ...; st.push(v); ... } catch (Stack::Full) {...} catch (Stack::All) {...}

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-17

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Resource Acquisition is Initialization
void f1() { FILE *fp = fopen("toto", "w"); ... fclose(fp); } void f2() { String *ps = new String("hello"); ... delete ps; } void f3() { Sema.P(); ... Sema.V(); }
1996, 2002 Jean-Paul Rigault Version 3.1

(1)

Who is going to call fclose if an exception traverses this function? Who is going to delete ps if an exception traverses this function? Who is going to release the semaphore (Sema.V()) if an exception traverses this function?
3-18

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Resource Acquisition is Initialization
class My_File { FILE *fp; public: My_File(...) {fp = fopen(...);} ~My_File() {fclose(fp);} }; class Handle { String *ps; public: Handle(...) {ps = new String(...);} ~Handle() {delete ps;} }; class Lock { Semaphore& sema; public: Lock(Semaphore& s) : sema(s) {sema.P();} ~Lock() {sema.V();} };
1996, 2002 Jean-Paul Rigault Version 3.1

(2)

void f1() { My_File mf("toto", "r"); ... // No more need to call fclose() } void f2() { Handle h("hello"); ... // No more need to delete the String } void f3() { Lock l(Sema); ... // No more need to free the semaphore }
3-19

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Termination or Resume? C++ exceptions are propagated upward the calling chain Moreover if the catch clause itself does not contain a transfer instruction, control resumes at the end of the try block where the exception was caught
The end of the try block means after the last catch clause of the block

Therefore it is impossible to resume execution where the exception was thrown (i.e. just after throw) Everything is as if the calling chain had been lost
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-20

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Exceptions
Exceptions Should Remain Exceptional Exceptions should be reserved to exceptional situations! This is largely a matter of context
while ((c = getchar()) != EOF) {...}

Above, the end of file is an expected (and wished) event


try{ read(fd, &data_size, sizeof(int)); read(fd, buffer, data_size); } catch(End_Of_File) {...}

Above something to read was normally expected; indeed, here the end of file is exceptional
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-21

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


Motivation Make downward cast safe
class A { public: ... }; class B : public A { public: void f(); // not in A }; A *pa = ...; // may be pa points to a B? pa->f(); // FORBIDDEN: no method f() in A ((B *)pa)->f(); // OK, but is it reasonnable?

(1)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-22

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


Motivation (2)

Run Time Type Information has not to be built-in, since we have already virtual functions However it is more comfortable and safer to delegate its implementation to the compiler Generally the RTTI mechanism is only relevant when accessing objects through pointers or references In other cases, static typing is performed

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-23

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


Operator dynamic_cast Use with a pointer p
T *pt = dynamic_cast<T *>(p)

(1)

Return 0 if p does not point to an object of type T or (publicly) derived from T; otherwise return the cast result Use with a reference r
T& rt = dynamic_cast<T&>(r);

Throw exception bad_cast if r does not reference an object of type T or (publicly) derived from T Require that T be a polymorphic type
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-24

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


Operator dynamic_cast
class Figure { public: virtual void rotate(int); virtual int surface() const; virtual void draw() const; }; class Ellipse : public Figure { public: Ellipse(Point c, int a, int b); int a_axis() const; int b_axis() const; }; class Circle : public Ellipse { public: Circle(Point c, int r) : Ellipse(center, r, r) {} int radius() const; };
1996, 2002 Jean-Paul Rigault Version 3.1

(2)
Figure *pf1 = new Circle(c0, R); Figure *pf2 = new Ellipse(c1, A, B); Ellipse *pe; Circle *pc; x = pf1->a_axis();// NO pe = dynamic_cast<Ellipse *>(pf1); // pe != 0 x = pe->a_axis();// YES... now pc = dynamic_cast<Circle *>(pf2); // pc == 0 pc = dynamic_cast<Circle *>(pf1); // pc != 0 char *p = dynamic_cast<char*>(pf1); // does not compile since char is // not polymorphic
3-25

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


Class type_info and Operator typeid (1)

Once dynamic_cast built into the language, the path is short to dynamic type identification A type descriptor (an instance of the predefined class type_info) is associated with each type (and thus with each class) Operator typeid returns a reference to the type descriptor of its parameter
const type_info& typeid(type-name); const type_info& typeid(expression);

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-26

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


Class type_info and Operator typeid Class type_info (#include <typeinfo>)
class type_info { public: virtual ~type_info(); bool operator==(const type_info&) const; bool operator!=(const type_info&) const; bool before(const type_info&) const; // !! const char *name() const; // No public constructor // No public copy operator };

(2)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-27

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


Class type_info and Operator typeid
Figure *pf = new Circle(...); typeid(pf) == typeid(Figure *) typeid(pf) == typeid(Ellipse *) typeid(pf) == typeid(Circle *) typeid(*pf) == typeid(Figure) typeid(*pf) == typeid(Ellipse) typeid(*pf) == typeid(Circle) // yes // no // no // no // no // yes

(3)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-28

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


Class type_info and Operator typeid typeid and dynamic_cast behaves like virtual functions A virtual function is statically bound when called from within a base class constructor (and destructor)
class A {public: A(void; ...}; class B : public A {...}; A::A() if // if // } { (typeid(*this) == typeid(B)) ... FALSE, even when we are constructing a B (dynamic_cast<B *>(this) != 0) ... still FALSE, even when we are constructing a B

(4)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-29

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


Bad Use of RTTI
void f(Figure *pf) { if (typeid(*pf) == typeid(Ellipse)) // do what is needed for an Ellipse else if (typeid(*pf) == typeid(Circle)) // do what is needed for an Circle else if (typeid(*pf) == typeid(Rectangle)) // do what is needed for an Rectangle else ... } In such a case, use virtual functions!
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-30

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


The Zoology of ANSI C++ Casts static_cast : a cast using only compile-time information
T1 t1; T2 t2 = static_cast<T2>(t1);
Contrarily to dynamic_cast, static_cast uses only static (compile-time) information Respect const and access control Not a dynamic mechanism, thus unsafe; it always returns something, possibly a nonsense If the cast is possible with only static information, it returns the correct value, even in case of ordinary multiple inheritance the result is always correct if the cast corresponds to an implicit conversion this cast must not be used in case of virtual multiple inheritance for downward casting
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-31

(1)

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


The Zoology of ANSI C++ Casts reinterpret_cast : the wild cast
T1 t1; T2 t2 = reinterpret_cast<T2>(t1);

(2)

T1 and T2 may have any pointer type or, more generally, any integral type This cast is intrinsically unsafe
it respects const (this is almost its only guarantee!) No adjustment of the value returned in case of multiple inheritance (contrarily to static_cast) The only sensible use is as a conversion relay (convert into some type, then backward to the original type)
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-32

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Run Time Type Information (RTTI)


The Zoology of ANSI C++ Casts (3)

const_cast : the cast to turn constants into variables


void f(const char *s, volatile int *pv) { char *pc = const_cast<char *>(s); int *pi = const_cast<int *>(pv); ... }

The target type must be the original type but without const or volatile If the object is actually constant or actually volatile, the result is undefined!
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-33

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Multiple Inheritance
Reminders The same class cannot appear several times as a direct base class The inheritance graph must be acyclic (DAG) Ambiguities are detected at compile time (provided that they are effective) and must be statically resolved If a class appears as a base class through several inheritance paths, the default is to have (in the derived class) as many copies of the base class as there are inheritance paths If only one copy is suitable, use virtual derivation
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-34

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Multiple Inheritance
Virtual Derivation
class Vehicule { public: virtual double speed() const; ... }; // Suppose the following two classes // do not redefine speed() class Plane : virtual public Vehicule {...}; class Boat : virtual public Vehicule {...}; class Sea_Plane : public Plane, public Boat {...}; Sea_plane sp(...); v = sp.speed(); // No ambiguity here
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-35

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Multiple Inheritance
Construction of Virtual Base Classes (1)

Virtual base classes must be constructed exactly once (as any C++ object) They are constructed before any regular base class Thus they must Either be constructible by default Or be (explicitly) constructed by any (concrete) derivative, whatever how deep this derivative is in the hierarchy

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-36

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Multiple Inheritance
Construction of Virtual Base Classes
class A { public: A(int); // no default construction }; class B : virtual public A {...}; class C : public B { public: C(int i): A(i), B(...) {...}// C must construct its base A }; class D: public C{ public: // D must also construct A : D(int i): A(i), C(i){...} // the usual construction // relay does not work! };
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-37

(2)

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Multiple Inheritance
Conversions and Virtual Base Classes
class class class class A {...}; B1 : public virtual A {...}; B2 : public virtual A {...}; C : public B1, public B2 {...};

(1)
A* B1* B2* C* B2

class A

members specific to B1 members specific to B2 members specific to C

B1

B2
Just a principle outline

C
1996, 2003 Jean-Paul RIGAULT Version 3.1

3-38

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Multiple Inheritance
Conversions and Virtual Base Classes (2)

The complexity of conversions and addressing explains why virtual derivation is not the default in C++ Note that pointers to members take into account this complexity Operator dynamic_cast makes downward cast possible for virtual base classes
static_cast does not give a correct result in case of virtual inheritance

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-39

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


General Picture Possibility to create functions and classes templates parametrized (mainly) with types Two different mechanisms for functions and classes Although somewhat homogenized by ANSI C++ Static resolution (compile and link time)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-40

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Functions: Definition Only one representation of identical operations, but on different types
template <typename T> inline T Min(T a, T b) { return a < b ? a : b; }

T denotes here any C++ type (class or built-in)... ... as long as the type has operator < and a copy constructor (possibly defined by default)
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-41

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Functions: Instantiation Instantiation is generally implicit
int i, j; char x, y; j = Min(i, 3); y = Min(x, y); // int Min(int, int) // char Min(char, char)

Implicit instantiation is within the responsibility of overloading resolution

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-42

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Functions: Specialization The previous form of Min is not suitable for C character strings Of course, the programmer may provide a regular function that will supersede template instantiation because exact exact match precedes template instantiation during overloading resolution
char *Min(char *s1, char *s2) { return strcmp(s1, s2) < 0 ? s1 : s2; } Note that this is different from template specialization (further)
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-43

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Functions: Utilization Generic functions are perfect replacement for the preprocessor macros with parameters
#define Min(a, b) ((a) < (b) ? (a) : (b))

By the way: eradicate most preprocessor use in C++


#define N 100 #define F(a) ... #define G(a) ... const int N = 100; inline F(int a) {...} template <typename T> inline T G(T a) {...}

There may remain only lexical and syntactic uses of the preprocessor
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-44

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Classes: Definition One unique representation of a set of classes that differ only by the types of objects they manipulate or possibly by some constants
template <typename Elem> class List {...};

template <typename Elem, int N> class Fixed_Array { Elem tab[N]; ... };
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-45

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Classes: Definition of Member and Friend Functions
template <typename Elem> class List { public: List(); void append(const Elem& e); friend ostream& operator<< <>(ostream&, const List<Elem>&); ... }; template <typename Elem> void List<Elem>::List() {...} template <typename Elem> void List<Elem>::append(const Elem& e) {...} template <typename Elem> ostream& operator<<(ostream& os, const List<Elem>& l) {...}

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-46

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Classes: Instantiation Generic class instantiation must be explicit
List<int> l1; List<List<int> > l2; // attention: > > Fixed_Array<double, 1000> fa1; Fixed_Array<List<int>, 100> fa2; List<Fixed_Array<List<char>, 10> > l3; typedef List<int> List_int; List_int l4;

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-47

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Classes and Class Derivation Both mechanisms are totally compatible
template <typename T> class A {...}; template <typename T> class B : public A<T> {...}; template <typename T> class Shared : public T {int refcnt; ...}; class C : public A<int> {...}; template <typename T> class D : public C {...};
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-48

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Classes and Friendship Friendship with all generic instances
template <typename T> class Vector { friend void f(); ... }; void f() {...}

Friendship with a specific generic instance


template <typename T> class Vector { friend void g<>(T); friend void h<>(const Vector<T>&); ... }; template <typename T> void g(T t) {...}
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-49

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Classes: Initialization of Static Members
template<typename T> class A { static T s; }; template <typename T> T A<T>::s = T(); // This initialization must be in the // same scope as the definition of the class

Omitting this initialization causes a link-time error

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-50

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Member Template and Friends Member Template (cannot be virtual)
class A { ... template <typename U> void mt(U u, ...); ... }; template <typename U> void A::mt(U u, ...);

(1)

Member template of a template class (cannot be virtual)


template <typename T> class A { ... template <typename U> void mt(U u, ...); }; template <typename T> template <typename U> void A<T>::mt(U u, ...);
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-51

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Member Template and Friends Template friend
class A { ... template <typename U> friend void tf(U u, ...); ... }; template <typename U> void tf(U u, ...);

(2)

Template template friend


template <typename T> class A { ... template <typename U> friend void tf(U u, ...) { ... } // better be defined inline! ... };

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-52

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Parameters for Classes and Functions ANSI C++ unifies the parameter possibilities for template functions and classes A generic parameter may be A type (built-in or class) A static constant of any integral type (this includes enum and also pointers to functions and pointers to members) Another generic class Default values are possible
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-53

(1)

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Parameters for Classes and Functions (2)

template <typename T, void (*SORT)(T, T[])> class Sortable {...}; void sort(int, int[]); Sortable<int, sort> s(...); template <typename T = int, int N = 10> class Fixed_Array {...};
template <typename U, template <typename T> class Container = list> class Something {...}; ... Something<int, vector> sth;
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-54

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Classes and Implicit Conversions Is there an implicit conversion from List<int> to List<double>? Let French be a class derived from Human. Is there an implicit conversion from Set<French> to Set<Human>? The answer is NO for both questions Should the answer be yes, contravariance (and thus the substituability principle) would be violated Two generic instances represent different types as soon as their (effective) generic parameters are different
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-55

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Explicit Instantiation of Generic Functions Introduced by ANSI C++ Necessary for generic functions without type parameter Useful help for the compiler and the linker Compilers know they must generate code here
template class List<int>; template void List<int>::append(const int&); // template void List<int>::append; template int Min<int, int>(int, int); // template Min<int, int>;
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-56

(1)

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Explicit Instantiation of Generic Functions Needed when the compiler cannot guess how to instantiate the template
template <int N> void f(); f(); // which value for N? f<10>(); // OK double x = Min(5, 7.2); double x = Min<double>(5, 7.2); // ambiguity // OK

(2)

Beware: possible syntactic ambiguities


template <int N> void f(int); i = f<3>(j); // it can be: (f<3) > (j) i = template f<3>(j); // OK
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-57

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Classes: Total Specialization It is possible to provide a specialized version of a generic class The specialized version supersedes generic instantiation
template <> class List<char *> { // Something which should // look like List<T> with T = char *, // although this is not necessary // (for C++) };
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-58

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Classes: Partial Specialization
template <typename T, typename I> class Vector { ... T& operator[](I index); }; template <> // Total specialization class Vector<void *, int> { ... void *& operator[](int index); }; // Note: no template <> void *& Vector<void *, int>::operator[](int index) { ... } template <typename T>// Partial specialization class Vector<T *, int> : public Vector<void *, int> { ... T*& operator[](int index); }; template <typename T> T *& Vector<T *, int>::operator[](int index) { ... }
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-59

(1)

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Generic Classes: Partial Specialization Any template function or class may be totally specialized Only classes may be partially specialized Regular functions and member functions cannot The specializations must be in the same namespace as the template definition See namespace further (2)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-60

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


The Problem of Automatic Template Instantiation The C++ compiler must generate code for the instantiation of generic functions and classes The user (instantiator) of a class usually sees only the class specification (.H). Where is the compiler supposed to find the body (.C)?
Use the ISO C++ export facility? Few compilers support it Find automatically the .C file in the include search path (-I option)? Use a configuration file? Put everything into the .H file (include .C into .H)?
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-61

(1)

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


The Problem of Automatic Template Instantiation (2)

In which object-file (.o) must the compiler generate the corresponding binary code? Generate static functions in the current compilation unit?
the code for the same template instance will be duplicated in several compilation units

Generate template code by demand in some repository and use a pre-link processor? Generate special code in the current compilation unit and rely on smart linker to collapse duplicated code? Rely on explicit template instantiation?
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-62

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Automatic Template Instanciation: AT&T C++/Sun CC Generate external functions If the specification of a class is in toto.H, the compiler looks for its implementation in toto.C by default File toto.C must also be in the #include search path The compiler generates code in a subdirectory (ptrepository, Templates.DB...) and handles chronological dependency with the source The compiler finds which template are to be instantiated by simulating link edition (unresolved symbols)
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-63

(1)

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Automatic Template Instantiation: AT&T C++/Sun CC
source-files (except template) #include .H files (template) .C files (template)

(2)

CC (compiler)

Some references still unsolved

Source generation

Object-files (except template)

Source-files (template)

Simulated link edition All references solved Link edition

CC (compiler)

Object-files (template)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-64

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Generic Functions and Classes (template)


Automatic Template Instantiation: GNU gcc 2.9x gcc requires the full definition of the template It does not yet support export Thus it is necessary to put everything into the .H file or to include the .C into the .H On systems supporting ELF binaries (Solaris, Linux...) gcc generate the instantiated template code in each compilation unit and relies on its own linker to collapse the duplicated code
The object files may become huge! But the resulting executable is smaller (than the sum of object files)
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-65

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Miscellaneous ANSI C++ Extensions


Summary New keywords Miscellaneous extensions (goodies) Scope of loop indexes; variables in conditions Pointer to class members Name packaging (namespace, using)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-66

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Miscellaneous ANSI C++ Extensions


Keywords
and and_eq asm auto bitand bitor bool break case catch char class compl const const_cast continue default delete do double dynamic_cast else enum explicit extern false float for friend goto if inline int long mutable namespace new not not_eq operator or or_eq private protected public register reinterpret_cast return short signed sizeof static static_cast struct switch template this throw true try typedef typeid typename union unsigned using virtual void volatile wchar_t while xor xor_eq

Legend:

break class throw bitand

already in ANSI C introduced in C++ (3.0) introduced by ANSI C++ introduced by ANSI C++ as an alternative denotation for some operators (same sort of brain damage as trigraphs!)
3-67

1996, 2003 Jean-Paul RIGAULT Version 3.1

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Miscellaneous ANSI C++ Extensions


Really Miscellaneous Support for European and extended characters Booleans (bool, true, false) Overloading resolution takes enum into account Constructors or conversion operators with explicit conversion (explicit)
class A { public: explicit explicit ... }; A a = 3; // a = 5; // A(int); operator double() const;

(1)

OK, invoke constructor implicit user conversion A(5) forbidden


3-68

1996, 2003 Jean-Paul RIGAULT Version 3.1

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Miscellaneous ANSI C++ Extensions


Really Miscellaneous Non constant members even in constant objects (mutable) Allow to reduce the number of casts removing const? Similar to const and volatile (but only applicable to class members) Direct initialization of const static integer members
class Table { const static int N = 10; int t[N]; };
1996, 2003 Jean-Paul RIGAULT Version 3.1

(2)

// OK // OK
3-69

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Miscellaneous ANSI C++ Extensions


Really Miscellaneous Relaxing the return type of a function overridden (redefined) in a derived class (covariance)
class A { ... A& f(int, double); }; class B : public A{ ... B& f(int, double); };
1996, 2003 Jean-Paul RIGAULT Version 3.1

(3)

// OK: redefines f

3-70

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Miscellaneous ANSI C++ Extensions


Really Miscellaneous Forward declaration of nested classes
class List { class Cell; Cell *first; ... }; // OK, defined later // OK

(4)

class List::Cell { ... };

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-71

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Miscellaneous ANSI C++ Extensions


Scope of Loop Indexes; Variables in Conditions If the loop index is declared in the for clause, its scope is limited to the loop body (including the for clause)
for (int i = 0; i < N; i++) if (t[i] == x) break; t[i]++; // NO: i is unknown here

In the same spirit, variables may be defined in conditions (in if or in loops)


if (int c = ...) {// c is only known here} while (int c = ...) {// c is only known here}
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-72

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Pointers to Class Members


Motivation Define a function taking a member-function as parameter
class Window { int width, height; int cursor_x, cursor_y; public: void up(); void down(); void right(); void left(); void repeat( ??? , int n); };
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-73

(1)

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Pointers to Class Members


Motivation What is the type of up, down... ? Certainly not void (*)() because class membership must be taken into account Pointer to a member-function of class Window with no parameter nor result
void (Window::*)()

(2)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-74

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Pointers to Class Members


Utilization of Pointers to Member-Functions Value
typedef void (Window::*Movements)(); Movements tab[] = {&Window::up, &Window::down, ...};

Through a pointer
void Window::repeat(void (Window::*op)(), int n) { for (int i = 0; i < n; ++i) (this->*op)(); }

Through an instance or a reference


void afunction(void (WIndow::*op)(), Window& w) { (w.*op)(); }
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-75

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Pointers to Class Members


Pointers to Data Members
class A { ... int x; int y; ... };

int A::*pmi = &A::x; A a, *pa = &a; ... a.*pmi = 12; // a.x = 12 pmi = &A::y; pa->*pmi = 27: // pa->y = 17

pointers to data members are sorts of portable offsets


1996, 2003 Jean-Paul RIGAULT Version 3.1 3-76

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Pointers to Class Members


Standard Conversions of Pointers to Members A pointer to a base class member can be implicity converted into a pointer to a derived class member
class A { int x; }; class B : public A { ... };

int A::*pma = &A::X B b; b.*pma = 12; // OK: b.x b.A::x = 12

Note that this conversion goes into the direction opposite to the other inheritance conversions
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-77

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Name Packaging (namespace)


Motivation Avoid name collisions due to an unique global name space when merging programs when using several libraries... Classes were already name spaces Explicit qualification (::) was required outside the class, though

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-78

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Name Packaging (namespace)


Definition
namespace My_Lib { class List {...}; void f(int, double); int f(char); ... }

A namespace is open : it can be extended simply by opening a new namespace clause with the same name The anonymous namespace is guaranteed collision-free Name spaces can be nested
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-79

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Name Packaging (namespace)


Utilization
My_Lib::List l; My_Lib::f(3, 12.5); int i = My_Lib::f('a'); using My_Lib::f; f(3, 12.5); int i = f('a'); // using declaration

using namespace My_Lib; // using directive List l; f(3, 12.5); int i = f('a');
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-80

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Name Packaging (namespace)


Synonyms
namespace Ecole_Superieure_en_Sciences_Informatiques { ... }

namespace ESSI = Ecole_Superieure_en_Sciences_Informatiques;

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-81

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Name Packaging (namespace)


Backwards Compatibility (1)

Standard ISO C++ library are in a predefined name space (std) Standard ANSI C .h files are also part of ISO C++, but their name is prefixed by c (e.g., <cstdio.h>, <cstring.h>, <cctypes.h>...) All standard ANSI C functions are part of the std namespace (prinft, sin...)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-82

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Name Packaging (namespace)


Backwards Compatibility Standard C++ .h files (e.g., <iostream.h>, <string.h>) are terminated with a using std directive The files with the same names but without extension .h (e.g., <iostream>, <string>...) do not include this using directive Unary operator :: allows access to a particular name space, the global space BEWARE: this global space is different from std, hence some risks of incompatibility with previous programs
1996, 2003 Jean-Paul RIGAULT Version 3.1 3-83

(2)

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Name Packaging (namespace)


Class as a Namespace Classes are namespace Directive using namespace is forbidden in a class Declaration using for an inherited member allow to locally import the member or to adjust its access control level (1)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-84

Advanced C++ Programming

3. Advanced Mechanisms and ANSI Extensions

Name Packaging (namespace)


Class as a Namespace
class A {public: void f(char);}; class B : public A { public: using A::f; // import A::f void f(int); // overloading, not hiding } class C : private A{ public: using A::f; // makes A::f public in C }; // the previous notation // A::f is now obsolete

(2)

1996, 2003 Jean-Paul RIGAULT Version 3.1

3-85

References

[1]

Andrei ALEXANDRESCU Modern C++ Design: Generic Programming and Design Patterns Applied

[6]

James O. COPLIEN Advanced C++: Programming Style and Idioms

Addisson Wesley, 2001


A fascinating book about template programming in C++. Certainly difficult but worht the effort for would-be C++ experts. [2] ANSI Technical Committee X3J11 Rationale for the ANSI C Programming Language [7]

Addison Wesley, 1992


Each language has its specific constructs, its idioms. This book describe some of the most important C++ idioms. Indispensible for mastering C++. James O. COPLIEN Multi-Paradigm Design for C++

Silicon Press, 1990.


Why is ANSI C as it is and not better? [3] John BARNES Programming in ADA [8]

Addison Wesley, 1999


C++ as a multi-paradigm language (that is supporting several programming styles). Brad J. COX Object-oriented Programming: an Evolutionary Approach

(4th Edition), Addison Wesley, 1995


A classical book on ADA. Also includes ADA 95. [4] Grady BOOCH Object-Oriented Analysis and Design with Applications [9]

Addison Wesley, 1986


The book on Objective C.

(2nd Edition), The Benjamin/Cummings Publishing Co, 1994.


Grady BOOCH wrote several reference text books on object-orientation. This is one of them. The examples are given in C++. [5] Don BULKA, David MAYHEW Efficient C++: Performance Programming Techniques [10]

Margaret ELLIS, Bjarne STROUSTRUP The Annotated C++ Reference Manual

Addison Wesley, 1990


THe reference on C++ version 2.1, but also the basis for tLa rfrence she ANSI/ISO Committee work. Somewhat obsolete now. Erich GAMMA, Richard HELM, Ralph JOHNSON, John VLISSIDES Design Patterns: Elements of Reusable Object-Oriented Software

Adison-Wesley, 2000
Make C++ run fast, avoid the inefficiency pitfalls.

Addison Wesley, 1995


The book on Design Patterns. Profound and innovative. A must read.

1996-2003 Jean-Paul R IGAULT Version 3.1

B-1

Programmation avance en C++


[11] Adele GOLDBERG, David ROBSON SmallTalk-80: the Language [18] Andrew KOENIG, Barbara MOO Ruminations on C++

Bibliographie commente

Addison Wesley, 1989


The reference on SmallTalk-80 (version 2). [12] Mats HENRICSON, Erik NYQUIST Industrial Strength C++ [19]

Addison Wesley, 1997


Programming quiz, idioms, advices. Instructive with humour. Stanley B. LIPPMAN, Josee LAJOIE C++ Primer

Prentice Hall, 1997


The practice and coding conventions in C++ within an important swedish telecommunication company. [20] [13] International Standard for Information Systems: Programming Language C++

(3rd Edition), Addison Wesley, 1998


An excellent introduction to C++ programming. Tony MASON, Doug BROWN lex and yacc

ISO/IEC 14882:1998(E)
The standard itself. Not really a tutorial! [14] Nicolai M. JOSUTTIS The C++ Standard Library [21]

OReilly Associates, Inc, 1991.


All you want to know about Lex and Yacc, the UNIX lexical and syntactic analyzers generators. Bertrand MEYER Object-oriented Software Construction

Addison Wesley, 1999


An excellent book about the C++ STL. [15] Brian W. KERNIGHAN, Rob PIKE The UNIX Programming Environment [22]

Prentice Hall International Series in Computer Science, 1988


Beyond a presentation of EIFFEL, the ideas of Bertrand MEYER about objectoriented programming and design.. Another must read. Bertrand MEYER EIFFEL: the Language

Prentice Hall Software Series, 1984


A classic book on the UNIX environment and the small is beautiful approach. [16] Brian W. KERNIGHAN, Denis M. RITCHIE The C Programming Language (ANSI C) [23]

Prentice Hall Object-Oriented Series, 1992.


The reference on the EIFFEL language. Presentation of high quality. Scott MEYERS Effective C++: 50 Specific Ways to Improve your Programs and Designs

(2nd Edition), Prentice Hall Software Series, 1988


The most recent edition of a book which has set up a reference on the C language, since 1978. Essentially the same book, but updated to ANSI C. [24] [17] Bjrn KIRKERUD Object-oriented Programming with SIMULA

Addison Wesley Professional Computer Series, 1992.


50 advices (and sometimes recipes) for C++ programmers. Very instructive. Scott MEYERS More Effective C++: 35 New Ways to Improve your Programs and Designs

Addison Wesley, 1989


PFor an introduction to SIMULA, the first object-oriented language.

Addison Wesley Professional Computer Series, 1995.


The sequel of the previous book. Same quality.

1996-2003 Jean-Paul R IGAULT Version 3.1

B-2

Programmation avance en C++


[25] Scott MEYERS Effective C++ CD: 85 Specific Ways to Improve your Programs and Designs [31] Peter WEGNER The Object-Oriented Classification Paradigm

Bibliographie commente

Addison Wesley Professional Computer Series, 1995.


The two previous books in CD ROM form. Very handy to browse the various advices and examples.. [26] Greg NELSON System Programming with Modula-3

in Research Directions in Object-Oriented Programming, pp 479-560, Bruce Shiver et Peter Wegner (diteurs), The MIT Press, 1988.
An attempt to model the object-oriented concepts by a prestigious author. Always instructive.

Prentice hall Series in Innovative Technology, 1991


A good introduction to Modula-3, another object-oriented language. [27] Bjarne STROUSTRUP The C++ Programming Language

(3rd Edition), Addison Wesley, 1997


The books of Bjarne on C++ have improved with time. This third edition is really excellent, with a complete coverage of C++ and the Standard Template Library, and many examples. [28] Bjarne STROUSTRUP The Design and Evolution of C++

Addison Wesley, 1994


Why is C++ as it is. The stoy about the definition of the language and its standardization process. How the features of C++ were introduced into the language? And, at least as interesting, why some features were rejected. A fascinating, one of a kind, book. Before criticizing C++, please read it! [29] Herb SUTTER Exceptional C++

Addison Wesley, 2000


All you wanted to know (and even more) about C++ exceptions, their use, their idoms, their semantics, their pitfalls... [30] Herb SUTTER More Exceptional C++

Addison Wesley, 2002


All you dear not ask about C++ exceptions, their use, their idoms, their semantics, their pitfalls...

1996-2003 Jean-Paul R IGAULT Version 3.1

B-3

You might also like