Library: Udžbenici Book Number: 16
Main Editor: prof. dr Safet Krkić
Technical Review: prof. dr Senad Burak prof. dr Dražena Tomić
Language Review: Authors
Book Covers: Mirza Hadžikadunić DTP: Authors
Copyright © Authors, 2005 FIT Mostar, 2005 Edicions de la Universitat de Leida, 2005
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the copyright owners.
Printed by Štamparija "FOJNICA" d.o.o. Fojnica
Supported by TEMPUS project CD JEP 16110-2001
CIP Katalogizacija u publikaciji Edicions de la Universitat de Leida Nacionalna i univerzitetska biblioteka Bosne i Hercegovine, Sarajevo
004.42(075.8)
RIBO, Josep Maria RIBO, Josep Maria Introduction to OOP with C++ / Introduction to OOP with C++ / Josep Maria Ribo, Ismet Maksumić, Josep Maria Ribo, Ismet Maksumić, Siniša Čehajić – Mostar: Siniša Čehajić – Mostar: Univerzitetska knjiga, 2005. – 333. str: graf. prikazi; 25 cm. – (Biblioteka Udžbenici; knj. 16)
Bibliografija: str. 331-332
ISBN 9958-603-22-5 ISBN 84-8409-199-6 1. Maksumić, Ismet 2. Čehajić, Siniša 1. Maksumić, Ismet 2. Čehajić, Siniša COBISS.BH-ID 14230534
Published by Univerzitetska knjiga Mostar, 2005 Edicions de la Universitat de Leida, 2005
Josep Maria Ribó Ismet Maksumić Siniša Čehajić
Introduction to OOP with C++
Published by Univerzitetska knjiga Mostar Edicions de la Universitat de Leida, July, 2005
Table of contents
Chapter 1: Principles od OOP. Classes. Objects...... 1 1.1. Modelling concepts...... 1 1.1.1. Abstract types...... 2 1.2. Concept of class ...... 4 1.3. Concept of object ...... 10 1.3.1. State ...... 11 1.3.2. Behaviour...... 11 1.3.3. Identity ...... 12 1.3.4. Classes vs. objects...... 13 1.3.5. The object orientation programming paradigm...... 14 1.4. Class contracts ...... 15 1.4.1. Defining a class contract...... 16 1.4.2. Preconditions...... 16 1.4.3. Postconditions...... 20 1.4.4. Class invariants ...... 21 1.4.5. Correctness of a class implementation...... 23 1.4.6. Example: Contract for the class Date...... 24 1.5. Detailed class and object definition in C++...... 26 1.5.1. Private and public members...... 29 1.5.2. Operation declaration and implementation ...... 30 1.5.3. Object creation...... 30 1.5.4. Access to members ...... 37 1.5.5. References vs. pointers ...... 39 1.5.6. Splitting class definition into different files...... 40 1.6. Some (pleasant) consequences of class definition ...... 42 1.7. Guided problems. The class MyString...... 44 1.7.1. The problem...... 44 1.7.2. Solution...... 45 1.7.3. The file Makefile...... 50 1.8. Guided problems. The word counter...... 50 1.8.1. The class WordCounter ...... 50 1.8.2. A client program ...... 56 1.8.3. The class WordCounterInterface...... 57 Chapter 2: Special members ...... 61 2.1. Constructors ...... 61 2.1.1. Notion of constructors...... 61 2.1.2. Constructor overloading...... 64 2.1.3. Default constructor...... 65 2.1.4. Default parameters ...... 65 2.1.5. Copy constructor...... 66 2.1.6. Construction call in the creation of arrays of objects...... 71 2.1.7. Creation of temporary objects...... 71 2.1.8. Dynamic object construction ...... 72
2.1.9. Construction of dynamic arrays of objects...... 73 2.1.10. An example ...... 74 2.2. Destructors ...... 75 2.2.1. Why are destructors necessary? The garbage ...... 75 2.2.2. The operator delete...... 78 2.2.3. Destructors in C++...... 78 2.2.4. Destruction of dynamic objects...... 80 2.2.5. Destructors and sharing of identity: warnings ...... 81 2.3. Friend functions and classes ...... 83 2.4. Operator overloading ...... 85 2.4.1. Operator = ...... 85 2.4.2. Operator ==...... 88 2.4.3. Operator []...... 89 2.4.4. Operator ()...... 90 2.4.5. Operators << and >>...... 91 2.5. What operations any C++ class should offer ...... 92 2.6. Guided problems. The class MyString...... 92 2.6.1. Solution: File MyString.h...... 93 2.6.2. Solution: File MyString.cpp...... 93 2.6.3. Solution: File userString.cpp ...... 97 Chapter 3: Generic classes and functions...... 99 3.1. Generic classes...... 99 3.1.1. Implementation of operations out of the template class definition ...... 102 3.1.2. Templates with more than one template parameter and non-type parameters...... 103 3.2. Generic functions...... 103 3.2.1. Incorporating functions as template parameters ...... 106 3.2.2. Explicit instantiation of a template function ...... 108 3.3. File organization with templates...... 109 3.4. Guided problems: A generic stack...... 110 3.4.1. The problem...... 110 3.4.2. Solution: File Stack.h...... 111 3.4.3. Solution: File userStack.cpp...... 113 Chapter 4: Associations. Composite objects. References ...... 117 4.1. Associations, aggregations and compositions...... 117 4.1.1. Associations ...... 117 4.1.2. Aggregations...... 120 4.1.3. Compositions ...... 121 4.1.4. A usual interpretation of aggregations...... 124 4.2. Constructors and destructors with subobjects...... 124 4.2.1. Construction...... 124 4.2.2. Destruction...... 128 4.3. Equality, copies and clones...... 129 4.3.1. Equality...... 129 4.3.2. Copy...... 136 4.3.3. Clone...... 142
4.4. Guided problem: The cyclic player...... 143 4.4.1. The class Player ...... 143 4.4.2. A careless deep copy for Player...... 143 4.4.3. A more cautious deep copy for Player...... 145 4.4.4. Generalizing the process of getting a deep copy...... 148 Chapter 5: Inheritance ...... 149 5.1. The meaning of inheritance...... 149 5.1.1. Class generalization and substitution principle...... 149 5.1.2. Subclasses and inheritance...... 151 5.1.3. Subclasses in C++...... 153 5.2. Constructors and destructors in derived classes...... 156 5.2.1. Constructors ...... 156 5.2.2. Destructors ...... 160 5.3. Member visibility and type of inheritance ...... 161 5.3.1. Member visibility...... 161 5.3.2. Types of inheritance...... 162 5.4. Different good (and bad) uses of inheritance...... 165 5.4.1. Specialization...... 165 5.4.2. Interface ...... 166 5.4.3. Similarity...... 168 5.4.4. Generalization...... 172 5.4.5. Instantiation...... 173 5.4.6. Multiple inheritance ...... 173 5.4.7. Association...... 174 5.5. Guided problem: A hierarchy of persons...... 176 5.5.1. The problem...... 176 5.5.2. Solution: The class Date ...... 177 5.5.3. Solution: The hierarchy of persons ...... 178 5.5.4. Solution: A client that tests constructors and destructors ...... 179 Chapter 6: Polymorphism...... 183 6.1. Concept of polymorphism...... 183 6.2. Class conformance...... 187 6.2.1. Class conformance rule...... 187 6.2.2. Static type conversion of references and pointers...... 191 6.2.3. Dynamic type conversion of references and pointers ...... 192 6.2.4. User defined type conversion...... 195 6.3. Dynamic binding and virtual functions...... 197 6.3.1. The problem of early binding...... 197 6.3.2. Virtual functions ...... 199 6.3.3. Call to virtual functions ...... 200 6.4. Pure virtual functions and abstract classes...... 203 6.5. Virtual constructors and destructors ...... 207 6.5.1. Virtual constructors...... 207 6.5.2. Virtual destructors...... 209 6.6. Multiple inheritance...... 210 6.6.1. Inheritance of different members with the same signature ...... 212
6.6.2. The same member inherited along different paths...... 217 6.7. Polymorphic behaviour of friend functions ...... 219 6.8. Guided problem: Multiple inheritance. A double hierarchy of persons...... 220 6.8.1. Presentation of the double hierarchy...... 220 6.8.2. Incorporating multiple inheritance...... 222 6.8.3. Virtual inheritance ...... 224 6.8.4. Polymorphism and virtual inheritance (1)...... 227 6.8.5. Polymorphism and virtual inheritance (2)...... 229 6.9. Guided problems: A polymorphic and generic stack...... 231 6.9.1. The problem...... 231 6.9.2. Solution...... 231 6.9.3. An improvement to the class Stack...... 238 6.10. Guided problem: A polymorphic hierarchy of containers ...... 239 6.10.1. The problem...... 239 6.10.2. Why this hierarchy? ...... 240 6.10.3. Abstract class Container...... 240 6.10.4. Abstract class Stack ...... 243 6.10.5. Class ArrayStack...... 243 6.10.6. Class LinkedStack...... 246 6.10.7. Comparison between both implementations ...... 249 6.10.8. Using the stack implementations ...... 249 6.10.9. And a dynamic cast...... 251 6.11. Guided problem: Stack of stacks ...... 251 6.11.1. The problem...... 251 6.11.2. Solution hint...... 252 Chapter 7: Exceptions ...... 255 7.1. Exceptions in computer programs...... 255 7.2. Exception handling in C++ ...... 257 7.3. Exceptions specification ...... 265 7.4. Exceptions in Java...... 268 7.5. Guided problem: Array based stack class ...... 270 7.5.1. The problem...... 270 7.5.2. Simple solution ...... 271 7.5.3. More robust solution ...... 273 7.6. Guided problem: Vector class...... 276 7.6.1. The problem...... 276 7.6.2. The solution ...... 276 7.6.3. More robust solution (1) ...... 279 7.6.4. More robust solution (2) ...... 284 Chapter 8: Standard C++ Library ...... 285 8.1. What is the "Standard C++ Library"...... 285 8.2. Strings ...... 286 8.3. STL Containers and Iterators ...... 288 8.3.1. Sequential containers ...... 292 8.3.2. Associative containers...... 297 8.4. STL Algorithms ...... 300
8.4.1. find() ...... 300 8.4.2. search()...... 301 8.4.3. sort()...... 302 Appendix A: UML ...... 307 A.1 UML evolution...... 307 A.2 Some aspects of the UML...... 309 A.3 The Basic Building Blocks of UML ...... 310 A.3.1 Model elements (things)...... 310 A.4. Relationships...... 315 A.4.1. Association...... 315 A.5 The UML Diagrams...... 321 A.5.1 Use-Case Model Diagrams ...... 322 A.5.2 Static Structure Diagrams ...... 324 A.5.3 Interaction diagrams...... 327 A.5.4 State Diagrams ...... 329 A.5.5 Implementation diagrams...... 329 Bibliography ...... 331 Index...... 333
Chapter 1 Principles of OOP. Classes. Objects
1.1. Modelling concepts One important problem that a software engineer must face when he/she is to develop a software application in a specific domain is the following: The application domain is packed with human-oriented, high-level concepts (e.g., student, academic subject, professor, bill, etc.), which offer several natural ways to interact with them (e.g., a student may be enrolled in a subject, a professor may be responsible for some subjects, a student should pay an enrolment bill, etc.). However, the constructs offered by traditional programming languages (i.e., those which are not either object-oriented or object-based languages) to map those concepts are usually quite low-level and machine-oriented (array, integer, pointer...). The immediate consequence of this abstraction gap between what is needed by the software developer and what is offered by the programming language is that any piece of software, ranging from medium-size programs to huge applications, becomes increasingly difficult to construct, test, maintain and reuse. The object-oriented programming (OOP) paradigm aims at bridging this abstraction gap, so that, we can construct a software application using directly entities that represent high-level domain concepts (student, subject, date, etc.). Probably, the most natural way in which a programming language can declare and use such high-level entities is by allowing the definition of new kinds of types (in addition to the predefined types as integer, char, array...). In the same way as predefined types are defined in terms of a set of operations that can be applied to the entities of those types (e.g., the predefined type integer has the operations +, -, *, / and remainder associated to; these operations can be applied to integers) it makes perfectly sense to define new high-level types giving the list of services they offer to their prospective users. To keep the same notation as with predefined types, we will call operations to the services offered by these new high- level types. Example We have to build an application to manage the academic issues of a university (e.g., syllabus, students, subjects, professors, enrolment, etc). In this context we can define a high-level type called Subject to refer to academic subjects so that it provides the following services or operations: • Set/get the title of the subject • Set/get the professor who is responsible for it
- 1 - CHAPTER 1: PRINCIPLES OF OOP. CLASSES. OBJECTS
• Set/get the contents of the subject • Set/get the term in which it is offered • Get the students enrolled in it • Add a new student enrolled in the subject • ... In this context, we may declare an entity sbj of type Subject and then set/get the title or the professor of sbj using the provided operations. ♦ ♦ ♦ Example As a part of the design of a race simulation application we have to model the concept of car. For that reason we may define a new high-level type called Car with the following services: • Start the car engine • Select the moving direction (ahead, reverse) • Move the steering-wheel some degrees to the right/left • Increase speed some kilometres per hour (accelerate) • Reduce speed some kilometres per hour (brake) • Switch on/off the lights • ... ♦ ♦ ♦ Notice that there can be different modelling of the same concept, corresponding to the various views that different users may have of that concept. For example, if the notion of car was modelled for a workshop management application, then the list of services should be different (e.g., date of the last oil change, problems detected in the car and not solved yet, state of the tyres, etc.).
1.1.1. Abstract types This modelling of high-level concepts by means of the definition of new types which provide a list of services constitutes a way to model concepts based on abstraction.