Version 3.1— June 2003 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 : 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: © 1996-2003 — Jean-Paul R IGAULT — Version 3.1 II 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 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 What’s in a Class? 2-8 The “Natural” Generalization of struct 2-9 A Model for Creating Instances 2-11 A Model for Creating Instances: new and delete 2-12 An (Abstract) Data Type 2-16 An (Abstract) Data Type: Redefining Operators 2-17 A Name Space 2-18 A Name Space: Hierarchical in case of Inheritance 2-19 An Encapsulation Unit 2-20 An Encapsulation Unit: Protected Members 2-21 A Reuse Unit through Inheritance 2-22 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 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 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 Multiple Inheritance 3-22 3-22 3-24 3-26 3-30 3-31 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 Miscellaneous ANSI C++ Extensions Summary Keywords Really Miscellaneous Scope of Loop Indexes; Variables in Conditions Pointers to Class Members Motivation Utilization of Pointers to Member-Functions Pointers to Data Members Standard Conversions of Pointers to Members Name Packaging (namespace) Motivation Definition Utilization Synonyms Backwards Compatibility Class as a Namespace References © 1996-2003 — Jean-Paul R IGAULT — Version 3.1 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 3-66 3-66 3-67 3-68 3-72 3-73 3-73 3-75 3-76 3-77 3-78 3-78 3-79 3-80 3-81 3-82 3-84 B-1 V Advanced C++ Programming © 1996-2003 — Jean-Paul R IGAULT — Version 3.1 Slides list VI 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 : jpr@essi.fr © 1996, 2003 – Jean-Paul RIGAULT — Version 3.1 0-1 Advanced C++ Programming Advanced C++ Programming Contents of the Course Introduction Fundamental Mechanisms in C++ Advanced Mechanisms and ANSI Extensions © 1996, 2003 – Jean-Paul RIGAULT — Version 3.1 0-2 Advanced C++ Programming Introduction © 1996, 2003 – Jean-Paul RIGAULT — Version 3.1 1-1 Advanced C++ Programming Introduction Introduction Summary ❏ C++ characteristics ❏ The object-oriented approach ❏ References © 1996, 2003 – Jean-Paul RIGAULT — Version 3.1 1-2 Advanced C++ Programming Advanced Mechanisms and ANSI Extensions Pointers to Class Members Motivation (2) ❏ 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::*)() © 1996, 2003 – Jean-Paul RIGAULT — Version 3.1 3-74 Advanced C++ Programming 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 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 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 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 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 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 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 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., , , ) ◆ 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 Advanced Mechanisms and ANSI Extensions Name Packaging (namespace) Backwards Compatibility (2) ❏ Standard C++ h files (e.g., , ) are terminated with a using std directive ❏ The files with the same names but without extension h (e.g., , ) 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 Advanced C++ Programming Advanced Mechanisms and ANSI Extensions Name Packaging (namespace) Class as a Namespace (1) ❏ 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 © 1996, 2003 – Jean-Paul RIGAULT — Version 3.1 3-84 Advanced C++ Programming Advanced Mechanisms and ANSI Extensions Name Packaging (namespace) Class as a Namespace (2) 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 © 1996, 2003 – Jean-Paul RIGAULT — Version 3.1 3-85 References [1] Andrei ALEXANDRESCU Modern C++ Design: Generic Programming and Design Patterns Applied [6] Addisson Wesley, 2001 Addison Wesley, 1992 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 Each language has its specific constructs, its “idioms” This book describe some of the most important C++ idioms Indispensible for mastering C++ [7] Silicon Press, 1990 John BARNES Programming in ADA James O COPLIEN Multi-Paradigm Design for C++ Addison Wesley, 1999 Why is ANSI C as it is and not better? [3] James O COPLIEN Advanced C++: Programming Style and Idioms C++ as a multi-paradigm language (that is supporting several programming styles) [8] (4th Edition), Addison Wesley, 1995 Brad J COX Object-oriented Programming: an Evolutionary Approach Addison Wesley, 1986 A classical book on ADA Also includes ADA 95 The book on Objective C [4] Grady BOOCH Object-Oriented Analysis and Design with Applications [9] (2nd Edition), The Benjamin/Cummings Publishing Co, 1994 Addison Wesley, 1990 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 Adison-Wesley, 2000 Make C++ run fast, avoid the inefficiency pitfalls Margaret ELLIS, Bjarne STROUSTRUP The Annotated C++ Reference Manual THe reference on C++ version 2.1, but also the basis for tLa référence she ANSI/ISO Committee work Somewhat obsolete now [10] Erich GAMMA, Richard HELM, Ralph JOHNSON, John VLISSIDES Design Patterns: Elements of Reusable Object-Oriented Software 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 avancée en C++ [11] Adele GOLDBERG, David ROBSON SmallTalk-80: the Language Bibliographie commentée [18] Addison Wesley, 1989 Addison Wesley, 1997 The reference on SmallTalk-80 (version 2) [12] Mats HENRICSON, Erik NYQUIST Industrial Strength C++ Programming quiz, idioms, advices Instructive with humour [19] Prentice Hall, 1997 An excellent introduction to C++ programming [20] International Standard for Information Systems: Programming Language C++ All you want to know about Lex and Yacc, the UNIX lexical and syntactic analyzers generators The standard itself Not really a tutorial! Nicolai M JOSUTTIS The C++ Standard Library [21] Addison Wesley, 1999 Brian W KERNIGHAN, Rob PIKE The UNIX Programming Environment Beyond a presentation of EIFFEL, the ideas of Bertrand MEYER about objectoriented programming and design Another must read [22] Prentice Hall Software Series, 1984 Brian W KERNIGHAN, Denis M RITCHIE The C Programming Language (ANSI C) The reference on the EIFFEL language Presentation of high quality [23] (2nd Edition), Prentice Hall Software Series, 1988 50 advices (and sometimes recipes) for C++ programmers Very instructive [24] Bjørn KIRKERUD Object-oriented Programming with SIMULA Addison Wesley, 1989 Scott MEYERS Effective C++: 50 Specific Ways to Improve your Programs and Designs Addison Wesley Professional Computer Series, 1992 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 [17] Bertrand MEYER EIFFEL: the Language Prentice Hall Object-Oriented Series, 1992 A classic book on the UNIX environment and the “small is beautiful” approach [16] Bertrand MEYER Object-oriented Software Construction Prentice Hall International Series in Computer Science, 1988 An excellent book about the C++ STL [15] Tony MASON, Doug BROWN lex and yacc O’Reilly Associates, Inc, 1991 ISO/IEC 14882:1998(E) [14] Stanley B LIPPMAN, Josee LAJOIE C++ Primer (3rd Edition), Addison Wesley, 1998 The practice and coding conventions in C++ within an important swedish telecommunication company [13] Andrew KOENIG, Barbara MOO Ruminations on C++ Scott MEYERS More Effective C++: 35 New Ways to Improve your Programs and Designs Addison Wesley Professional Computer Series, 1995 The sequel of the previous book Same quality PFor an introduction to SIMULA, the first object-oriented language © 1996-2003 — Jean-Paul R IGAULT — Version 3.1 B-2 Programmation avancée en C++ [25] Scott MEYERS Effective C++ CD: 85 Specific Ways to Improve your Programs and Designs 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 Bibliographie commentée [31] Peter WEGNER The Object-Oriented Classification Paradigm 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 ... 1-7 Advanced C++ Programming Fundamental Mechanisms in C++ © 1996, 2003 – Jean-Paul RIGAULT — Version 3.1 2-1 Advanced C++ Programming Fundamental Mechanisms in C++ Fundamental Mechanisms in C++. .. — Version 3.1 2-10 Advanced C++ Programming Fundamental Mechanisms in C++ The C++ Class A Model for Creating Instances ❏ Internal data structure ◆ Underlying C structure ❏ Initialization and... Advanced C++ Programming 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