Evaluation TrainingCopy Centers

C++ TrainingPROGRAMMING Centers

Evaluation Copy Course # TCPRG3002 Rev. 3/8/2016

UMBC Training Centers | 6996 Columbia Gateway Drive, Suite 100 | Columbia, Maryland 21046 | [email protected] | 443-692-6600

C++ PROGRAMMING

Training Centers 6996 Columbia Gateway Drive EvaluationSuite 100 Columbia, MD 21046 Tel: 443-692-6600 Copyhttp://www.umbctraining.com

TrainingC++ PROGRAMMING Centers

Evaluation Copy

Course # TCPRG3002 Rev. 3/8/2016

©2016 UMBC Training Centers i C++ PROGRAMMING

EvaluationThis Page Intentionally Left Blank Copy

Training Centers

Evaluation Copy

©2016 UMBC Training Centers ii C++ PROGRAMMING

Course Objectives • At Evaluationthe conclusion of this course, students will be able to:  Explain how object-oriented software engineering enhances the software development process.  Identify the major elements in an object-oriented programming language. Copy  Implement the concepts of data abstraction and encapsulation in the creation of abstract data types.  Implement operator overloading.  Use inheritance in C++.  Select the proper class protection mechanism.  Demonstrate the use of virtual functions to implement polymorphism.  programs utilizing the I/O classes in C++.  UnderstandTraining some advanced features Centers of C++ including templates, exceptions, and multiple inheritance.

 Compare the object vs the procedural approach to writing software.  Use correct object oriented terminology.  EvaluationDefine and use classes in a C++ program.  Create and use abstract data types.  Derive classes using inheritance in C++.  Implement polymorphismCopy by using virtual functions in a program.

©2016 UMBC Training Centers iii C++ PROGRAMMING

EvaluationThis Page Intentionally Left Blank Copy

Training Centers

Evaluation Copy

©2016 UMBC Training Centers iv C++ PROGRAMMING

Table of Contents

CHAPTER 1: PERSPECTIVE The Software Crisis ...... 1-2 DesignEvaluation Techniques...... 1-4 Large Software Systems...... 1-5 Roots of Object Technology...... 1-6 What Is Object-Oriented Programming?...... 1-7 C++ and Object-Oriented Programming ...... 1-8 Why C++?...... 1-9 Features of C++...... 1-10Copy Pros and Cons of C++ ...... 1-11 CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION What Is an Object? ...... 2-2 What Is a Class?...... 2-5 Encapsulation ...... 2-8 Data Hiding...... 2-9 The Public ...... 2-11 Relationships Among Classes ...... 2-12 Inheritance...... 2-13 Polymorphism...... 2-17 Object-Oriented Design ...... 2-19 CHAPTER 3: C VS. C++ CommentsTraining ...... 3-2 Centers Namespaces...... 3-3 Simple Output...... 3-4 Simple Input...... 3-6 Definitions Near to First Use...... 3-7 Function Prototypes...... 3-8 The inline Specifier...... 3-9 const...... 3-10 StructureEvaluation Members ...... 3-13 The Reference Type ...... 3-14 Overloading Function Names ...... 3-20 Default Parameters...... 3-21 The Scope Resolution Operator ...... 3-24 Aggregates ...... 3-25 Operators new and deleteCopy...... 3-26 The bool ...... 3-28 The string Data Type ...... 3-29

CHAPTER 4: FUNDAMENTALS OF CLASSES Data Types ...... 4-2 User Defined Data Types ...... 4-4 Using the Class Concept ...... 4-5

©2016 UMBC Training Centers v C++ PROGRAMMING

Defining a Class...... 4-6 public and private Access Levels...... 4-9 The Scope Resolution Operator :: ...... 4-13 Using Class Objects Like Built-in Types ...... 4-17 ScopeEvaluation ...... 4-18 Constructors ...... 4-20 Member Initialization Lists ...... 4-24 Destructors ...... 4-26 Array of Objects...... 4-30 Pointers ...... 4-32 The this Pointer...... 4-34Copy Passing Objects to Functions ...... 4-36 Returning Objects From Functions ...... 4-38 static Class Members...... 4-39

CHAPTER 5: OPERATOR OVERLOADING Introduction...... 5-2 Rules for Operator Overloading...... 5-3 Rationale for Operator Overloading ...... 5-4 Overloading Member Functions...... 5-5 Overloading Non-Member Functions...... 5-10 friend Functions ...... 5-12 The Copy Constructor...... 5-15 The Assignment Operator...... 5-22 Overloading [ ]...... 5-28 OverloadingTraining Increment and Decrement OperatorsCenters ...... 5-29 const Objects and References...... 5-30 CHAPTER 6: COMPOSITION OF CLASSES Relationships ...... 6-2 Composition of Classes ...... 6-3 The Point Class...... 6-4 The Line Class...... 6-5 Member Initialization Lists ...... 6-6 An ApplicationEvaluation With Composition...... 6-7 The Copy Constructor Under Composition ...... 6-8 operator= Under Composition...... 6-9

CHAPTER 7: INHERITANCE Introduction...... 7-2 Public Base Classes...... 7-4Copy The protected Access Level ...... 7-9 Member Initialization Lists ...... 7-11 What Isn’t Inherited...... 7-15 Assignments Between Base and Derived Objects...... 7-16 Compile-Time vs. Run-Time Binding ...... 7-18 virtual Functions ...... 7-21

©2016 UMBC Training Centers vi C++ PROGRAMMING

Polymorphism...... 7-27 virtual Destructors ...... 7-28 Pure virtual Functions...... 7-29 Abstract Base Classes...... 7-31 An ExtendedEvaluation Inheritance Example...... 7-32 CHAPTER 8: I/O IN C++ The iostream Library ...... 8-2 Predefined Streams...... 8-3 Overloading operator<<...... 8-4 Overloading operator>>...... 8-7 Manipulators ...... 8-9Copy States...... 8-12 Formatted I/O...... 8-15 Disk Files ...... 8-17 Reading and Writing Objects ...... 8-22 CHAPTER 9: ADVANCED TOPICS Template Functions ...... 9-2 Template Classes...... 9-5 Multiple Inheritance...... 9-8 User-Defined Conversions...... 9-12 Data Structures...... 9-15 An Iterator Class...... 9-19 Exceptions ...... 9-23 CHAPTERTraining 10: INTRODUCTION TO THE STANDARD Centers TEMPLATE LIBRARY Introduction...... 10-2 The Standard Template Library ...... 10-3 Design Goals ...... 10-4 STL Components...... 10-6 Iterators ...... 10-8 Example: vector...... 10-9 Example: list ...... 10-10 Example:Evaluation ...... 10-11 Example: map ...... 10-12 Example: find ...... 10-13 Example: merge...... 10-14 Example: accumulate ...... 10-15 Function Objects...... 10-16 Adaptors ...... 10-20Copy APPENDIX A: INTRODUCTION Background...... A-2 Environmental Considerations...... A-5 A Sample C Program...... A-6 Variables and Data Types...... A-8 Arrays ...... A-11

©2016 UMBC Training Centers vii C++ PROGRAMMING

Example of a Program Using an int Array...... A-13 Components of a C Program ...... A-14 C Operators ...... A-15 Examples of the Operators ...... A-16 ControlEvaluation Structures...... A-17 Functions ...... A-19 Function Prototypes...... A-22 Simple I/O...... A-23 APPENDIX B: MORE I/O IN C The printf Function...... B-2 The scanf FunctionCopy ...... B-4 The Preprocessor ...... B-5 Conditional Compilation...... B-10 Avoiding Multiple Inclusion for the Same File ...... B-12 APPENDIX C: AGGREGATES IN C Data Types Revisited...... C-2 Aggregate Types ...... C-3 Arrays ...... C-4 Structures ...... C-6 Structures and Functions...... C-8 Fields...... C-10 Enumeration Types...... C-11 APPENDIX : POINTERS IN C Fundamental Concepts...... D-2 PointerTraining Operations...... Centers D-3 Using Pointers to Alter a Function Argument...... D-5 Using Pointers for Array Traversal...... D-6 Pointer Arithmetic ...... D-7 Sending an Array to a Function ...... D-10 Command Line Arguments ...... D-13 Pointers vs. Arrays...... D-14 Sending an Aggregate to a Function ...... D-15 SummaryEvaluation of the Uses of Pointers ...... D-18 APPENDIX E: BIBLIOGRAPHY Bibliography...... E-2 Copy

©2016 UMBC Training Centers viii C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

Chapter 1: EvaluationPerspective 1) The Software Crisis...... 1-2

2) Design Techniques ...... 1-4

3) Large Software Systems ...... 1-5 4) Roots of Object TechnologyCopy ...... 1-6 5) What Is Object-Oriented Programming?...... 1-7

6) C++ and Object-Oriented Programming ...... 1-8

7) Why C++?...... 1-9

8) Features of C++...... 1-10

9) Pros and Cons of C++...... 1-11

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 1-1 C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

The Software Crisis

• Business entities can gain a competitive edge with sound useEvaluation of computer software. • Hardware is moreCopy stable than software. • Software has been traditionally delivered late and over budget despite continued promis es of new techniques and methodologies.

 structured "everything"  case tools

• With the passage of time, new applications require more lines of code than ever. Problems appear faster than solutions.Training Centers • Older and more traditional languages were not built for programming in the large.

• Because of these factors, it has become normal for softwareEvaluation development efforts to be delivered late and over budget. This phenomenon has been called the software crisis. Copy

©2016 UMBC Training Centers 1-2 C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

The Software Crisis

• Engineers can systematically build large physical systems onEvaluation time.

• Large software systems have not been built as successfully as Copyother large systems.  Bridges

 Buildings  Destroyers

• Modular design of programming has been espoused for many years.

 Many programming languages support modular design features.  ModularizationTraining has usually focused Centers on procedures and not data.

Evaluation Copy

©2016 UMBC Training Centers 1-3 C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

Design Techniques

• Over the years, various design techniques have been usedEvaluation to solve the software crisis. However, the focus has been on algorithms and not data.  Functional DecompositiCopyon (Yourdon, Constantine) • Some techniques have concentrated on data moving through the system and not algorithms.

 Data Flow Diagrams (Gane, Sarson)

• The Object-Oriented approach is different from either of the above since it concentrates on both data and algorithms at the same time.

 Identifying objects of the system to be modeled  DetermineTraining behavior of those objects Centers  Solutions tend to closely model the problem

Evaluation Copy

©2016 UMBC Training Centers 1-4 C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

Large Software Systems

• Early computing systems were designed to solve specific andEvaluation narrow ranged problems.

• Languages typically evolve to meet the needs of newer and more complexCopy problems. • Today's problems are more complex than ever and cannot be solved with yesterday's languages. Therefore, newer technologies are needed.

• Each new technology claims to be the next panacea. In reality, new technologies usually solve tomorrow’s problems and yield a new set of problems. • Object-OrientedTraining technology is theCenters latest panacea, even though it has been around for many years now.

Evaluation Copy

©2016 UMBC Training Centers 1-5 C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

Roots of Object Technology

• Many of the concepts used in Object-Oriented technology EvaluationSimula were a part of the language (Dahl and Nygaard) developed in the late 1960s in Norway. • The notion of a Copyclass comes from Simula . A class is the way in which new data types are created.

• The term object-oriented first appeared in the Smalltalk language developed by Alan Kay at Xerox- PARC (Palo Alto Research Center).

• The Smalltalk language borrowed heavily from Lisp, which was developed by McCarthy in 1960 at Dartmouth College.Training Centers

Evaluation Copy

©2016 UMBC Training Centers 1-6 C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

What Is Object-Oriented Programming? • DefinitionsEvaluation of object-oriented programming abound.  It is a type of programming where programmers define the data type of a and the types of operations (functions) that can be applied to the data structure. In this way, the data structure becomes an object that includes both data and functions. In addition,Copy programmers can create relationships between objects. For example, objects can inherit characteristics from other objects.  It is a method of implementation in which programs are organized as collections of objects, each of which represents an instance of some class, and whose classes are all members of some hierarchy of classes united via inheritance.  It is programming by defining objects, their inter-relationships, and their behavior. • Training Centers Most definitions involve the following.  classes  objects  hierarchies  Evaluationinheritance • Each term will beCopy fully explained later.

©2016 UMBC Training Centers 1-7 C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

C++ and Object-Oriented Programming

• Programming in C++ is not necessarily writing object- orientedEvaluation programs. This is because C++ is not 100% object-oriented.

• C++ was designed by Bjarne Stroustrup from AT&T’s Murray Hill ResearchCopy Center. His specific design goals included making C++:  become a better C;  support data abstraction; and  support object oriented programming.

• Programmers tend to think of C++ as the object-oriented superset of ANSI C.

• ProgramsTraining in C++ can be object-oriented, Centers procedural, or a combination of both.

Evaluation Copy

©2016 UMBC Training Centers 1-8 C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

Why C++? • ThereEvaluation are many object-oriented languages. C++ Java Smalltalk Objective C Ada Modula 2 • In 2001, Java andCopy C++ were the two most popular objected-oriented languages in terms of the number of programmers writing developing projects.

• As time goes on, it is likely that the number of Java programmers will far exceed that of C++ programmers. This is largely due to the popularity of the World Wide Web.

• C++ has been highly successful, in part, because of the hugeTraining base of installed C language Centers programmers in the world.

• C programmers can apply C++ features gradually. There is very little new syntax to learn if you are a C programmer wishingEvaluation to write C++ code. • This would not be true if you were coming to C++ from Cobol or Fortran (or something other than C).

• Because C++’sCopy roots are buried in C, C++ is arguably the most efficient Object-Oriented language around.

©2016 UMBC Training Centers 1-9 C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

Features of C++

• C++ has many features that make it an attractive languageEvaluation in which to develop software.

 The standard C libraries can be used in all C++ programs.  C++ has its own set of standard libraries.  Run-time errorCopy handling is accomplished through the mechanism.  Type independent programming can be accomplished through templates.  C++ offers its own String data type. Training Centers

Evaluation Copy

©2016 UMBC Training Centers 1-10 C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

Pros and Cons of C++

• C++ is a very difficult language to learn. It has many "nooksEvaluation and crannies" which can lead a programmer astray.

• Memory management is the biggest problem. It is too easy for a programmerCopy to allocate memory without reclaiming it.

• C++ has many features, and it is not always clear which feature is the best one to use in order to implement a particular design.

• On the other hand, there are many accrued benefits when developing software using an object-oriented language. TheTraining ones most often cited are listedCenters below.  faster development time  decreased maintenance  code reuse  Evaluationbetter quality Copy

©2016 UMBC Training Centers 1-11 C++ PROGRAMMING CHAPTER 1: PERSPECTIVE

This Page Intentionally Left Blank

Evaluation

Copy

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 1-12 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Chapter 2: EvaluationThe Language of Object-Orientation 1) What Is an Object? ...... 2-2

2) What Is a Class?...... 2-5

3) Encapsulation ...... 2-8 4) Data Hiding...... Copy 2-9 5) The Public Interface ...... 2-11

6) Relationships Among Classes...... 2-12

7) Inheritance...... 2-13

8) Polymorphism ...... 2-17

9) Object-Oriented Design...... 2-19

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 2-1 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

What Is an Object?

• A plethora of words exists that are commonly used in object-orientation.Evaluation In this section, we wish to define and discuss them.

• The best place to start is to use Grady Booch's definition of an object. Copy "A tangible entity which exhibits some well defined behavior." • This implies that an object is something physical such as a:

 person;  building; or  computer. • However,Training an object can also beCenters conceptual.  Linked List  Banking Transaction

• In software, we can think of an object as a place in memoryEvaluation that contains a representation of something physical or conceptual.

• A designer would model this representation and a programmer wouldCopy implement it.

©2016 UMBC Training Centers 2-2 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

What Is an Object? • ForEvaluation example, a Date object might be represented as having a month, day, and year. A programmer would perhaps model this as shown below. int day; int month; int year; Copy

• As another example, a File object might be represented as containing a size, type, and creation date. Then, a programmer could model a file like that shown below. int size; string type; date created;

• An Traininginteger array object mightCenters contain a size and a pointer to the data. int size; int *data;

• A PersonEvaluation object might be represented as follows. string name; int age int height; int weight; color eyecolor;Copy color haircolor;

• Therefore, an object can be considered a compound variable (i.e., one with component parts).

©2016 UMBC Training Centers 2-3 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

What Is an Object?

• However, an object also has behavior. Each action that a designerEvaluation creates for an object is implemented by a programmer, via a function.

• In the object-oriented world, a function is also referred to as a method. Copy

• Therefore, a Date object may have the following methods. int getDay() bool isLeapYear() int getYear() bool isHoliday() int getMonth()

• A FileTraining object might have these Centers methods. int getSize() bool isNewer(date) string getType() date getCreateDate()

• Evaluation Therefore, each object has two principal characteristics  The state of an object is the collection of all of the data items of the object.  The behavior Copyof an object is the set of all methods for an object.

©2016 UMBC Training Centers 2-4 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

What Is a Class?

• If you write a program that simulates a small business, EvaluationPerson there would be many objects represented in the software.

• Each Person in the simulation will have the same data CopyPerson fields as any other in the simulation. Of course, the state of each Person will likely be different from any other Person.

 In other words, each Person object would have its own name field, but the value of my name field would be mike, while the value of your name field would likely be something else.

• The state and behavior of similar objects, such as Person, are defined in a higher order entity called a classTraining. Centers • Therefore, a class definition is a blueprint out of which copies of objects are created. A class defines the data fields and methods for a particular type of object. • Evaluation Each object can be thought of as an instance of a class. Each object will probably have a different set of data for its attributes. Object data is sometimes called instance data. Copy

©2016 UMBC Training Centers 2-5 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

What Is a Class? • HereEvaluation is an example of two different Person objects. Name Ken Barbie age 53 38 height 71 62 weight 190 105 eyecolorCopy blue brown haircolor brown brown

• Classes can also have data. This is different from object data.

 With object data, each object has its own data fields.

• The objects of the class share class data. Regardless of how many objects there are in a program, there is one instanceTraining of class data in the entire Centers program. • Class data is, in effect, global to the class and accessible by all objects of the class. Evaluation Copy

©2016 UMBC Training Centers 2-6 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

What Is a Class? • HereEvaluation are some examples of class data.  Eligible voting age – independent of any particular voter  Number of objects currently instantiated for a class – a count of all objects of a particular class currently allocated in memory Copy

obj 1 obj 2 obj 3

voting age = 18 Training Centers

Evaluation Copy

©2016 UMBC Training Centers 2-7 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Encapsulation • AnEvaluation object is, in effect, a compound variable. • A class is, in effect, a type with a well-defined behavior. • A class is definedCopy in C++ by using the class (or struct) keyword.

• A class defines a set of data and a set of operations. Class declarations are usually found in header files. // Person.h

class Person { string name; int age; Trainingint height; Centers int weight; Color eyecolor; Color haircolor;

/* class methods go here Evaluation */ };

• The coupling of data and functions is known as encapsulation.Copy

©2016 UMBC Training Centers 2-8 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Data Hiding • ConsiderEvaluation the program below that uses the Person class from the preceding page. #include "Person.h"

main() { Copy Person Jim;

Jim.age = 43; Jim.weight = 205;

/* Jim now goes on a diet and loses 20 pounds for his birthday */

Jim.age = 44; Jim.weight = 185; } Training Centers

• Keep in mind that when a new type (such as Person) is created, many programs will use it. Therefore, you would expect many programs to make references, as shown above.Evaluation Copy

©2016 UMBC Training Centers 2-9 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Data Hiding

• Now, suppose that the class designer decides to change theEvaluation representation of the class. // Person.h

class Person { Copy string name; int characteristics[3]; Color colors[2];

/* class methods go here */ }; • In the code on the previous page, all of the references to the data items are incorrect. • Training Centers A better solution is to disallow direct access to object data. This principle is called data hiding. Later in the course, youEvaluation will see how it is enforced. Copy

©2016 UMBC Training Centers 2-10 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

The Public Interface

• When data hiding is implemented, the user of a new data typeEvaluation must have another way to access object data.

• Access to “hidden” data is provided through a set of methods knownCopy as the public interface. • Therefore, a user of a class is presented with a public interface to a set of hidden data.

• In this way, the new type is abstract. The class exposes only the essential details while hiding the unessential details.

• This is not a new concept. Even a simple type such as int is abstract. Users use this type without needing to knowTraining how an is represented. Centers Therefore, you could consider that the data for an integer is hidden.

Evaluation Copy

©2016 UMBC Training Centers 2-11 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Relationships Among Classes

• Together with encapsulation, the defining characteristic of Evaluationobject-oriented programming is inheritance.

• Before object-oriented software development can begin, much time is spent in the analysis and design phases of the developmentCopy cycle.

• These phases will yield many classes that are part of the problem domain.

• Software is much more manageable when the solution closely models the real world problem.

• This is why the creation of objects is so important to softwareTraining development and maintenance. Centers • When one examines all the classes that are designed to satisfy analysis requirements, there will usually be some relationshipsEvaluation between these classes. Copy

©2016 UMBC Training Centers 2-12 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Inheritance

• Although there are many different kinds of relationships, theEvaluation most important kinds follow.  association – Person works for a Company  aggregation – Car has an Engine  generalizationCopy – Circle is a Shape

• When these relationships are implemented in software, then developers can take advantage of code reuse. That is, some of the methods from one class can be reused in another related class.

• Among all of these relationships, generalization is the one that makes a programming language object-oriented.

• DifferentTraining object-oriented languages Centers use different terminology to describe inheritance. When two classes are related through inheritance, they can be described as follows.

 type – subtype relationship  Evaluationsuperclass – subclass relationship  base class – derived class relationship

• In C++, the base class and derived class terminology is used. Copy

©2016 UMBC Training Centers 2-13 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Inheritance

• The inheritance relationship is often represented using the UnifiedEvaluation Modeling Language (UML) as follows.

DataStructure

Copy

Array List

• The arrows point up at their Base classes. Therefore, you can see that Array and List are both derived classes and that DataStructure is a base class. • InheritanceTraining is used to model theCenters is-a relationship. For example:

An Array is-a data structure. A List is-a data structure.

An Airplane is-a FlyingVehicle. A DC10Evaluation is-an airplane.

• Inheritance is deriving a specialized class from a more general class. Copy

©2016 UMBC Training Centers 2-14 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Inheritance

• The specialized class inherits both data fields and methodsEvaluation from its generalized class.  Inheritance leads directly to code reuse and/or interface reuse. • Subclasses canCopy add methods and/or data.

• Discovering classes and subclasses is the central theme of object-oriented design.

• Implementing classes is the central theme of object- oriented programming and this course.

• In the world of object-oriented programming, there are two groups of programmers - those who implement class designsTraining and those who use classes. Centers • In this course, you will often be playing both roles.  On the one hand, you will be implementing classes.  EvaluationOn the other hand, you will use them to test their correctness. Copy

©2016 UMBC Training Centers 2-15 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Inheritance

• We will take a peek at how inheritance is implemented. EvaluationEmployee Suppose we had an class. // Employee.h

class Employee { Copy double salary; string name;

void set_salary(double sal); double get_salary(); void set_name(string n); string get_name(); };

• We could now derive a Manager class from Employee. // TrainingManager.h Centers

#include "Employee.h"

class Manager : public Employee { string rank; Evaluation string benefits[5];

string get_rank(); string get_benefits(int n); }; Copy • Manager inherits the data items salary and name and the following methods. get_salary set_salary get_name set_name

©2016 UMBC Training Centers 2-16 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Polymorphism

• Programming languages generally allow the same operatorEvaluation symbol to have different meanings. This is referred to as operator overloading. We will study this in detail later in the course. int n1, n2, n3; float f1, f2,Copy f3;

n1 = n2 + n3; // + is overloaded f1 = f2 + f3; // + is overloaded

• Some programming languages allow functions to be overloaded. int ans, n[100]; float result, vals[100]

ansTraining = average(n, 100); Centers result = average(vals, 100);

• In the above examples, the same name (function overloading) or the same symbol (operator overloadingEvaluation) has caused different code to be executed.  Polymorphism is the more general name for this feature. Copy

©2016 UMBC Training Centers 2-17 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Polymorphism

• A more important of polymorphism centers on inheritance.Evaluation Suppose that we have the following classes. class Container {...};

class Shape {...}; Copy class Ellipse : public Shape { void draw(); }; class Rectangle : public Shape { void draw(); };

class Circle : public Ellipse { void draw(); }; class Square : public Rect { void draw(); }; • Now consider the following code, which adds various shapes to the container. Container myShapes;

Circle c; Square s; RectangleTraining r; Centers Ellipse e;

myShapes.add(&c); myShapes.add(&s); myShapes.add(&r); myShapes.add(&e);

Evaluation // Which draw function will be called?

for ( int i = 0; i < myShapes.size(); i++) myShapes [i]Copy -> draw(); • The capability of a language to select the “correct” method from a set of same-named methods in an inheritance hierarchy is called polymorphism.

©2016 UMBC Training Centers 2-18 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Object-Oriented Design

• This course is a programming workshop and not a course in EvaluationObject-Oriented Design. It can nevertheless be informative to mention the high-level steps, which take place in an object-oriented design.

• Here are the stepsCopy in an oversimplified Object-Oriented Design.  Pick out the classes from the application domain. • determine the attributes • determine the operations

 Determine the relationships among the selected classes. • generalization - specialization • aggregation •Training association Centers

 Be prepared to iterate over the above choices. Evaluation Copy

©2016 UMBC Training Centers 2-19 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Object-Oriented Design • WeEvaluation present an object-oriented design of a small business. • We first need to brainstorm and determine the classes present in any small business. Some possible candidates would be as follows.Copy Worker Clerk Manager SalesPerson MaintenanceWorker Engineer Accountant Lawyer MarketingPerson Inventory PayrollRecord SalesSlip PurchaseOrder BalanceSheet PandLStatement Catalog

• For each of the above, we would need to select the data fieldsTraining and the behaviors. Centers • For example, a PayrollRecord might have the following fields. Name Address PhoneNumber Department SalaryEvaluation StartDate SSN LastRaise JobTitle Copy EducationCode

©2016 UMBC Training Centers 2-20 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Object-Oriented Design • MethodsEvaluation for the PayrollRecord class might include the following. getname() getphone() getsalary() computebonus() daysSinceHired() getcode() daysToNextRaise()Copy gettitle() etc.

• Possible Inheritance Worker Support Accountant Lawyer Maintenance Medical Regular Clerk Training Manager Centers SalesPerson Engineer

FinancialStatement Internal PayrollRecord Evaluation SalesSlip PurchaseOrder External BalanceSheet PandLStatement CashFlowCopy

©2016 UMBC Training Centers 2-21 C++ PROGRAMMING CHAPTER 2: THE LANGUAGE OF OBJECT-ORIENTATION

Exercises

1. ListEvaluation some of the objects that are in your kitchen and define some relationships that exist among them (aggregation or generalization). 2. For each of the following classes, design the operations and the interfaceCopy for each. Fraction Mathematical Set Bank Account

3. Select any subject matter domain and find two classes. For each of them, list at least five attributes and at least five operations.

 How would you know if you have listed all of the attributes?  How would you know if you have listed all of the operations? Training Centers

Evaluation Copy

©2016 UMBC Training Centers 2-22 C++ PROGRAMMING CHAPTER 3: C VS. C++

Chapter 3: EvaluationC vs. C++ 1) Comments ...... 3-2

2) Namespaces...... 3-3

3) Simple Output ...... 3-4 4) Simple Input ...... Copy 3-6 5) Definitions Near to First Use...... 3-7

6) Function Prototypes...... 3-8

7) The inline Specifier ...... 3-9

8) const...... 3-10

9) Structure Members...... 3-13

10) The Reference Type ...... 3-14 11) OverloadingTraining Function Names ...... Centers 3-20 12) Default Parameters ...... 3-21 13) The Scope Resolution Operator...... 3-24

14) Aggregates ...... 3-25

15) Operators new and delete...... 3-26 16) TheEvaluation bool Data Type ...... 3-28 17) The string Data Type...... 3-29 Copy

©2016 UMBC Training Centers 3-1 C++ PROGRAMMING CHAPTER 3: C VS. C++

Comments • ExamineEvaluation the following program. // Example of C++ style of commenting // Nice for single line comments // Anything after the // // is taken as a comment // End of lineCopy ends each comment

main( ) { /* Notice also that older style C comments still exist and are nice for multi line comments. */ }

• C style comments are allowed but you cannot nest them. /* Training OK */ Centers

/* /* PROBLEM */ */

• C++ style comments are preferred. // //Evaluation These are C++ style comments. // They are preferred //

• Both comment stylesCopy can be used in the same program.

©2016 UMBC Training Centers 3-2 C++ PROGRAMMING CHAPTER 3: C VS. C++

Namespaces

• C++ has the capability of collecting names and placing themEvaluation in their own separate symbol table. This is accomplished in C++ by using the namespace keyword. • The most importantCopy function served by namespace is to prevent name collisions between items that have the same names in different libraries.

• You can define your own namespace to prevent collisions with other libraries that you might buy or download.

• C++ compilers come with the std namespace already defined. You will see this namespace in all of the programsTraining that we will be using Centersin this course.

Evaluation Copy

©2016 UMBC Training Centers 3-3 C++ PROGRAMMING CHAPTER 3: C VS. C++

Simple Output

• We now want to illustrate the way in which you can performEvaluation some simple output in a C++ program. There is an object named cout, which is defined in the std namespace. cout is mapped to your display.

• Copy<< This object has the insertion operator, , defined. Sometimes this is called the output operator. Therefore, if you want to insert some value into the output stream, you use cout, as will be shown shortly.

• The functions and operators (such as <<) for this object are defined in the file iostream. Therefore, you must include this file in any program that wishes to place data onto the display. • Training Centers The << operator can handle any of the built-in data types in C++. int x = 10; double y = 20.5; std::cout << x; std::cout << y; Evaluation  You can cascade your arguments as well. std::cout << "x= " << x << ", y = " << y ; Copy

©2016 UMBC Training Centers 3-4 C++ PROGRAMMING CHAPTER 3: C VS. C++

Simple Output • coutEvaluation is equivalent to the stdout in C programs. • All C++ programs can also use the printf standard C library function, but these programs must include the header file stdio.hCopy. • The << operator is easier to use than printf since it requires no formatting.

• Here is a sample program to demonstrate some of these ideas. 3-5.cpp

1. // 2. // 3-5.cpp 3. // 4. Training#include Centers

5. 6. int main( ) 7. { 8. int x = 10; 9. 10. std::cout << "x = " << x << "\n"; 11. std::cout << "x * x = " << x * x << "\n"; 12. Evaluation 13. return 0; 14. } Copy

©2016 UMBC Training Centers 3-5 C++ PROGRAMMING CHAPTER 3: C VS. C++

Simple Input • CorrespondingEvaluation to the object cout, there is an object named cin that is attached to your keyboard. This object is also part of the std namespace. • cin is equivalentCopy to the stdin in your C programs. • cin has an extraction operator, >>, which can grab items from the input stream as long as they are separated by whitespace.

• Here is a simple piece of code to illustrate the use of cin. 3-6.cpp

1. // 2. // 3-6.cpp 3. Training// Centers 4. #include 5. 6. int main( ) 7. { 8. int x, y; 9. 10. std::cout << "input a value "; 11. std::cin >> x; 12.Evaluation std::cout << "You input " << x << "\n";

13. std::cout << "input two values "; 14. std::cin >> x >> y; 15. std::cout << x << " * " << y 16. << " is " << x * y << "\n"; 17. 18. return 0;Copy 19. }

©2016 UMBC Training Centers 3-6 C++ PROGRAMMING CHAPTER 3: C VS. C++

Definitions Near to First Use

• In C++, you are not restricted to defining variables ahead of Evaluationany executable statements. You can write the following. int x; std::cout << "enter a value "; std::cin >> x;Copy int y; std::cout << "enter another "; std::cin >> y; • Bugs and debugging times are reduced when a variable is placed close to its first use. Training Centers

Evaluation Copy

©2016 UMBC Training Centers 3-7 C++ PROGRAMMING CHAPTER 3: C VS. C++

Function Prototypes

• The original C language did not perform type checking betweenEvaluation arguments and parameters.

• In ANSI C, the programmer was given a choice. If you used function prototypes, then the compiler performed type checking. CopyOtherwise, type checking was not performed.

• In C++, there is no choice. You must use prototypes. This means that you cannot invoke a function if the compiler has not seen the prototype for that function.

• Often the prototypes are brought into your program using include files.

• TheTraining small program below will notCenters compile because there is no prototype for the strcpy function. Of course, you

can fix the problem by including or . int main() { Evaluation char line[100]; strcpy(line, "data"); return 0; } Copy

©2016 UMBC Training Centers 3-8 C++ PROGRAMMING CHAPTER 3: C VS. C++

The inline Specifier • C++Evaluation provides the inline keyword. Functions, which have this specifier, will have their code executed inline and will avoid the cost of a function call. inline double min(double a, double b) { return a

• If you attempt to make a function inline and the compilerTraining rejects it, you will be givenCenters a warning. • An inline function is preferred over a macro because the latter cannot perform type checking nor can it guard against unwarranted side effects. #define MIN(A,B) (( (A ) < (B) ) ? (A) : (B)) Evaluation  The above macro will have an undesired double increment in the following code. int x = 5, y = 10, z; z = MIN(x++, Copyy++);

©2016 UMBC Training Centers 3-9 C++ PROGRAMMING CHAPTER 3: C VS. C++

const • TheEvaluation C++ language has many uses of the const keyword. Its simplest use is to replace #define directives from C. In other words, C++ prefers const int arraySize = 100;

to Copy

#define ARRAYSIZE 100

• arraySize is a read-only variable that must be initialized when it is defined. Thereafter, it cannot be modified, not even through a pointer. Therefore, the following attempt to modify arraySize through the pointer will not compile. int *p = &arraySize; // compiler error *p = 50; • However,Training the following is allowed. Centers That is, it is fine to const int const int * assign the address of a to a type. const int arraySize = 100; const int *p; p Evaluation= &arraySize // ok *p = 50; // illegal

• You still cannotCopy change the constant through the pointer.

©2016 UMBC Training Centers 3-10 C++ PROGRAMMING CHAPTER 3: C VS. C++

const

• The above type is commonly used as a safeguard against changingEvaluation an argument through a parameter. 3-11.cpp

1. // 2. // 3-11.cpp 3. // Copy 4. #include 5. 6. double average(const int *data, int amount); 7. 8. int main() 9. { 10. const int howmany = 5; 11. int x[ ] = { 10, 30, 115, -20, 11 }; 12. 13. double result = average(x, howmany); 14. 15. std::cout << result << "\n"; 16. 17. return 0; 18. Training} Centers 19. 20. double average(const int *data, int amount) 21. { 22. double sum = 0.0; 23. int i; 24. 25. for ( i = 0; i < amount; i++) 26. Evaluation sum += data[i]; 27. 28. return sum/amount; 29. } Copy

©2016 UMBC Training Centers 3-11 C++ PROGRAMMING CHAPTER 3: C VS. C++

const • YouEvaluation can also have a const pointer. This pointer cannot change. However, what it points to can change. int val = 20, x = 50; int *const cpi = &val; // const ptr to int *cpi = 35; // ok, changes val cpi = &x; Copy // illegal • C++ also allows a constant pointer to a constant value. In this case, neither the value or the pointer can be changed. int value; const int *const cptc = &value; Training Centers

Evaluation Copy

©2016 UMBC Training Centers 3-12 C++ PROGRAMMING CHAPTER 3: C VS. C++

Structure Members

• In C++, a structure can have data members and function members.Evaluation In fact, this is how encapsulation is achieved. A structure encapsulates data and functions. Here is an example. 3-13.cpp Copy 1. // 2. // 3-13.cpp 3. // 4. #include 5. 6. struct Fraction 7. { 8. int n; 9. int d; 10. 11. void recip( ) { 12. int temp; 13. temp = n; 14. n = d; 15. Training d = temp; Centers 16. } 17. 18. void print( ){ 19. std::cout << n << "/" << d << "\n"; 20. } 21. }; Evaluation • Function members are accessed just like data members. struct Fraction a; // define a Fraction a.n = 3; // assign value to n a.d = 5; Copy // assign value to d a.print( ); // print it a.recip( ); // exchange n and d a.print( ); // print it

©2016 UMBC Training Centers 3-13 C++ PROGRAMMING CHAPTER 3: C VS. C++

The Reference Type

• In C++, the reference type is used to ease the burden that comesEvaluation from using pointers. Rather than use indirection with a pointer, you can use a reference as a synonym for a variable.

• Notice the role ofCopy the pointer in the following code. int val = 20; int *pt = &val; // px points to val std::cout << *pt; // print val

• You can perform the same task with a reference variable but with an easier notation. int val = 20; int & ref = val; // ref is synonym for val std::cout << ref; // print val Training Centers  ref is a reference to the integer val. Whenever you use the reference variable, you are actually using the value it is referencing.

• You can think of a reference as a self-dereferencing pointer.Evaluation  A reference must be initialized when it is defined. int x = 10; int & badrx; // syntax error int & rx = x;Copy // ok

©2016 UMBC Training Centers 3-14 C++ PROGRAMMING CHAPTER 3: C VS. C++

The Reference Type

• A reference can be used in most of the places where a pointerEvaluation had been formerly used in C. The result is that the user is freed from the pointer notation.

• For example, a C programmer would code a swap routine as follows. TheCopy user of swap must remember to pass addresses, while the writer of swap must remember to use pointer notation. void swap(int * a, int * b);

main( ) { int x = 25, y = 30; swap(&x, &y); }

voidTraining swap(int * a, int * b)Centers { int temp; temp = *a; *a = *b; *b = temp; } Evaluation Copy

©2016 UMBC Training Centers 3-15 C++ PROGRAMMING CHAPTER 3: C VS. C++

The Reference Type • WhenEvaluation swap is written using references, both of these burdens are lifted from the programmer. void swap(int & a, int & b);

main( ) { Copy int x = 25, y = 30; swap(x, y); }

void swap(int & a, int & b) { int temp; temp = a; a = b; b = temp; } • TheTraining prototype for swap tells the Centers compiler that a pass by reference is in effect. Therefore, a and x are

synonymous. Likewise, y and b are synonymous.

• More importantly, both the writer of swap and the user of swapEvaluation do not have to worry about the cumbersome notation, which pointers imply.

• Passing by reference gives the advantage of pointers without the disadvantageCopy of pointer notation.

• Large chunks of data, like structs and class objects, should be passed to functions by reference.

©2016 UMBC Training Centers 3-16 C++ PROGRAMMING CHAPTER 3: C VS. C++

The Reference Type

• A reference can also be returned from a function. This mayEvaluation be more difficult to understand, but in this case the invocation of the function is a synonym for whatever is being returned. 3-17.cpp Copy 1. // 2. // 3-17.cpp 3. // 4. #include 5. int x = 1; 6. int & f( ) 7. { 8. return x; 9. } 10. main( ) 11. { 12. int y; 13. y = f( ) + f( ); // f( ) == x 14. std::cout << y << "\n"; // prints 2 15. Training f( ) = y; Centers // x = 2 16. std::cout << x << "\n"; // prints 2 17. } • When a function returns a reference, it may be used on eitherEvaluation side of an assignment. • When passing by reference, if there is no intent to modify the passed value, then the parameter should be a const reference (const &). Therefore, you will be assured that the argument isCopy not modified by the function. • The following code does not pass by const &, so an error is introduced.

©2016 UMBC Training Centers 3-17 C++ PROGRAMMING CHAPTER 3: C VS. C++

The Reference Type 3-18.cpp 1. Evaluation// 2. // 3-18.cpp 3. // 4. #include 5. struct Fraction 6. { 7. int n, d;Copy 8. 9. Fraction mult(Fraction & param) 10. { 11. param.n *= n; 12. param.d *= d; 13. return param; 14. } 15. void print() 16. { 17. std::cout << n << "/" << d << "\n"; 18. } 19. }; 20. int main() 21. { 22. Training struct Fraction a, b, c;Centers 23. a.n = 1; 24. a.d = 3; 25. b.n = 2; 26. b.d = 5; 27. c = a.mult(b); 28. a.print(); 29. b.print(); 30. Evaluation c.print(); 31. return 0; 32. }

• The code above correctly multiplies the two fractions. However, upon Copyreturn from the function, the argument b has been modified.

• The correct way to write this function is shown next.

©2016 UMBC Training Centers 3-18 C++ PROGRAMMING CHAPTER 3: C VS. C++

The Reference Type 3-19.cpp 1. Evaluation// 2. // 3-19.cpp 3. // 4. #include 5. 6. struct Fraction 7. { Copy 8. int n, d; 9. 10. struct Fraction mult(const Fraction & p) 11. { 12. struct Fraction temp; 13. temp.n = p.n * n; 14. temp.d = p.d * d; 15. return temp; 16. } 17. void print() 18. { 19. std::cout << n << "/" << d << "\n"; 20. } 21. }; 22. Training Centers 23. int main() 24. { 25. struct Fraction a, b, c; 26. a.n = 1; 27. a.d = 3; 28. b.n = 2; 29. b.d = 5; 30. Evaluation c = a.mult(b); 31. a.print(); 32. b.print(); 33. c.print(); 34. return 0; 35. } Copy • In this version of the multiply function, the parameter is a const &. Any attempt to modify it will result in a compiler error.

©2016 UMBC Training Centers 3-19 C++ PROGRAMMING CHAPTER 3: C VS. C++

Overloading Function Names

• In most cases, each function has a unique name. However,Evaluation when different functions perform the same task on different data types, it is convenient for these functions to have the same name.

• This concept is Copycalled function overloading. The compiler selects the proper function based on the type of the argument(s) sent to the function. int square(int v) { return v * v; }

double square(double v) { return v * v; } Training Centers

int square (int * v) { return *v * *v; }

intEvaluation main( ) { int a, b = 5;

a = square(b); // square(int) double x, y = 25.5; x = square(y);Copy // square(double) int *p = &b; a = square(p); // square(int *)

return 0; }

©2016 UMBC Training Centers 3-20 C++ PROGRAMMING CHAPTER 3: C VS. C++

Default Parameters • ConsiderEvaluation the gets function from the standard C library. char line[SOME_LINE_SIZE]; gets(line); • It would be more convenient if this function were overloaded as follows.Copy Of course, C does not allow this. gets(line); // read until a newline gets(line, '.'); // read until a period gets(line,','); // read until a comma • Although the solution above works fine in C++, the developer still needs to write two functions.

• C++ allows another way to implement the above convenience, default parameters. • Training Centers With this strategy you can write one function but allow default parameters if the user does not supply all possible parameters.

• For example, the Fraction structure could add a function memberEvaluation named setFraction, which could be invoked in any of the following ways. struct Fraction A;

A.setFraction(2,1);Copy A.setFraction(0); A.setFraction();

©2016 UMBC Training Centers 3-21 C++ PROGRAMMING CHAPTER 3: C VS. C++

Default Parameters • TheEvaluation code for setFraction would appear within the Fraction structure. struct Fraction { … … Copy … void setFraction(int numer = 0, int denom = 1) { n = numer; d = denom; } };

• If fewer than two arguments are given, then the default values are used. A.setFraction(0);Training // same Centersas A.setFraction(0,1); A.setFraction(); // same as A.setFraction(0,1);

Evaluation Copy

©2016 UMBC Training Centers 3-22 C++ PROGRAMMING CHAPTER 3: C VS. C++

Default Parameters

• Default values for parameters can apply to any function, notEvaluation just those within structures. 3-23.cpp

1. #include 2. 3. void print(charCopy *s, int start = 0) 4. { 5. std::cout << s + start << std::endl; 6. } 7. 8. int main( ) 9. { 10. char *string = "useful"; 11. print(string); // prints 'useful' 12. print(string, 3); // prints 'ful' 13. char *string2 = "parameter"; 14. print(string2); // prints 'parameter' 15. print(string2, 4); // prints 'meter' 16. 17. return 0; 18. Training} Centers

• Default values can only be applied to the rightmost set of parameters. In other words, the following would be an error.Evaluation void setValues(int a = 0, int b, int c = 1) { … } Copy

©2016 UMBC Training Centers 3-23 C++ PROGRAMMING CHAPTER 3: C VS. C++

The Scope Resolution Operator

• In C and in C++, parameters and local variables hide namesEvaluation from the global scope.

• In C++, the scope resolution operator is used to access elements from theCopy global scope.

3-24.cpp

1. #include 2. 3. int n1 = 50, n2 = 100; 4. 5. void fun( ) 6. { 7. std::cout << n1 << std::endl; // prints 50 8. std::cout << n2 << std::endl; // prints 100 9. } 10. 11. main( ) 12. Training{ Centers 13. int n1 = 500, n2 = 1000; 14. 15. fun(); 16. 17. std::cout << n1 << std::endl; // prints 500 18. std::cout << n2 << std::endl; // prints 1000 19. 20. Evaluation std::cout << ::n1 << std::endl; // prints 50 21. std::cout << ::n2 << std::endl; // prints 100 22. } Copy

©2016 UMBC Training Centers 3-24 C++ PROGRAMMING CHAPTER 3: C VS. C++

Aggregates • In EvaluationC and C++, aggregates are defined in the same way. struct Address { int number; string street, city, state; long zip; }; Copy

enum Boolean {Yes, No};

union Hash { char string[4]; long int index; };

 Caution: Do not forget the semi-colon after each definition.

• However, in C++, you can relax the definitions of each of theTraining items above. Centers main( ) { Address Home, Work; Boolean IsMember; Hash Word; Evaluation ..... }

• Therefore, in all of the previous examples, the line: struct FractionCopy A;

could have been written as: Fraction A;

©2016 UMBC Training Centers 3-25 C++ PROGRAMMING CHAPTER 3: C VS. C++

Operators new and delete • In EvaluationC++, the operators new and delete play the role of malloc and free. They allow programs to allocate storage dynamically. Casts are unnecessary when using these operators. char *pc Copy= new char; int *pi = new int; Fraction *pp = new Fraction;

pp -> numer = 3; pp -> denom = 5; pp -> recip( ); pp -> print( );

• Arrays of any type can also be allocated by using the operator new. Since new returns 0 when there is not enough memory to honor the request, programmers shouldTraining check for this condition. Centers Fraction *ratios = new Fraction[10]; if (ratios == 0) cout << "Memory allocation failed" << endl; else for (i = 0; i < 10; i++) Evaluation ratios[i].print( );

• Memory obtained with new must be deallocated with delete. There are two forms of delete that can be used. The correctCopy one to use depends upon how the storage was initially obtained in your program.

©2016 UMBC Training Centers 3-26 C++ PROGRAMMING CHAPTER 3: C VS. C++

Operators new and delete • If youEvaluation requested an array, then use the following form. delete [ ] ratios;

If not, then use the form below.

delete pc; Copy delete pi; delete pp; • It cannot be stressed enough that these two operators must be used in connection with one another. You will also find out soon that these operators cause other important actions in C++.

• Notes  OnlyTraining use [ ] form of delete onCenters arrays.  Only use delete on storage obtained by using new.  It is fine to delete storage from a pointer whose value is 0. Evaluation Copy

©2016 UMBC Training Centers 3-27 C++ PROGRAMMING CHAPTER 3: C VS. C++

The bool Data Type • In Evaluationaddition to the C language data types like char, int , float, double, short, long, unsigned, and derivatives, C++ adds an important fundamental type. • This is the boolCopy data type. A bool can store only the values true and false. Notice the way in which this type can be used.

• The bool data type can be used in any of the following ways. 3-28.cpp

1. // 2. // 3-28.cpp 3. // 4. # 5. Training#include Centers 6. bool isBigger(int p1, int p2) 7. { 8. return p1 > p2; 9. } 10. int main() 11. { 12. int x, y; 13. Evaluation std::cout << "enter two integers "; 14. std::cin >> x >> y; 15. bool isGreater = x > y; 16. if ( isGreater ) 17. std::cout << x << " gt " << y << "\n"; 18. 19. isGreaterCopy = isBigger(x, y); 20. if ( isGreater ) 21. std::cout << isGreater << "\n"; 22. return 0; 23. }

©2016 UMBC Training Centers 3-28 C++ PROGRAMMING CHAPTER 3: C VS. C++

The string Data Type • C Evaluationprograms have using the char * type to implement strings for many years. char *mystring = "hello"; char line[100]; strcpy(line, mystring); std::cout << Copymystring[0] << "\n"; • C++ uses the string data type. This data type should be used rather than char * whenever possible.

• When you use strings, you are actually using objects, so we will defer a more complete treatment of this topic. However, we will give a small example of the use of strings. 3-29.cpp 1. Training// Centers 2. // 3-29.cpp 3. // 4. #include 5. #include 6. int main() 7. { 8. std::string simple("must include"); 9. Evaluation std::cout << simple << "\n"; 10. simple.append(" string"); 11. std::cout << simple << "\n"; 12. std::cout << simple.length() << "\n"; 13. std::cout << simple[0] << "\n"; 14. std::string phrase; 15. phrase = Copysimple; 16. phrase.append(" to work. "); 17. std::cout << simple << "\n"; 18. std::cout << phrase << "\n"; 19. return 0; 20. }

©2016 UMBC Training Centers 3-29 C++ PROGRAMMING CHAPTER 3: C VS. C++

The string Data Type • TheEvaluation first thing you may have noticed is that you must include the header file string in order to use the string type. • Another importantCopy note is that the string type is part of the std namespace and therefore you must write:

std::string simple("must include");

when you are defining your strings.

• If your program gets cluttered with too many std references, you can mandate the global use of the std namespace with a using statement. If you do this, your codeTraining would appear as shown onCenters the next page. • Whichever way you choose, your output will be the same. The output of both programs (3-29 and 3-31) is also shownEvaluation on the next page. Copy

©2016 UMBC Training Centers 3-30 C++ PROGRAMMING CHAPTER 3: C VS. C++

The string Data Type 3-31.cpp 1. Evaluation// 2. // 3-31.cpp 3. // 4. #include 5. #include 6. 7. using namespaceCopy std; 8. 9. int main() 10. { 11. string simple("must include"); 12. cout << simple << "\n"; 13. simple.append(" string"); 14. cout << simple << "\n"; 15. cout << simple.length() << "\n"; 16. cout << simple[0] << "\n"; 17. 18. string phrase; 19. phrase = simple; 20. phrase.append(" to work. "); 21. cout << simple << "\n"; 22. Training cout << phrase << "\n"; Centers 23. 24. return 0; 25. }

• OutputEvaluation must include must include string 19 m must include string must include Copystring to work

©2016 UMBC Training Centers 3-31 C++ PROGRAMMING CHAPTER 3: C VS. C++

The string Data Type • TheEvaluation string data type has many other functions and operators. A few are shown below.

std::string myString("hello");

char letter =Copy myString[0]; // h

string part = myString.substr(0,2); // he

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 3-32 C++ PROGRAMMING CHAPTER 3: C VS. C++

Exercises

1. WriteEvaluation a C++ program that inputs two from the user. Write a function that squares both of the integers. The prototype for this function should be: void square(int & first, int & second);

Your program shouldCopy call this function from main() and display the results. 2. Take your solution to the previous exercise and add another function that overloads the square function so that it works for two doubles. The prototype for this function should be: void square(double & first, double & second);

Add additional statements to main() to test this new function.Training Centers

Evaluation Copy

©2016 UMBC Training Centers 3-33 C++ PROGRAMMING CHAPTER 3: C VS. C++

Exercises

3. AddEvaluation initialize, add, and divide functions to the code below and test each one of them. The initialize function should take two integer parameters and assign their values to the variables numer and denom. There is a starter file forCopy this exercise in the starters directory. 3-3.cpp

1. #include 2. using namespace std; 3. 4. struct Fraction 5. { 6. int numer; 7. int denom; 8. 9. void print( ) 10. { 11. Training cout << numer << Centers "/" << denom; 12. } 13. 14. void recip( ) 15. { 16. int temp = numer; 17. numer = denom; 18. Evaluation denom = temp; 19. } 20. 21. Fraction mult(const Fraction & p) 22. { 23. FractionCopy temp; 24. temp.numer = p.numer * numer; 25. temp.denom = p.denom * denom; 26. return temp; 27. } 28. };

©2016 UMBC Training Centers 3-34 C++ PROGRAMMING CHAPTER 3: C VS. C++

Exercises

4. CreateEvaluation a struct named Pair that has data items first and second. Both of these items should be of type string. There should also be a bool data item, which should be set to true or false depending upon whether the twoCopy strings are the same or not.  Get the strings from the command line and feed them to the structure using the first two functions shown below. Other functions of the struct should be as indicated. void setFirst(string) void setSecond(string)

string getFirst() string getSecond() bool areTheSame()

5. Create a struct named Mortgage with the following dataTraining items and functions. Centers double amount; // initial double rate; int years; double payment; // per month double balance; // owed Evaluationdouble principal; // per month double interest; // per month

void setValues (int yrs, double amt, double intRate); Copy double computePayment(); void makePayment(); double getBalance(); double getInterest(); double getPrincipal(); double getPayment();

©2016 UMBC Training Centers 3-35 C++ PROGRAMMING CHAPTER 3: C VS. C++

Exercises Exercise 5 (continued) TheEvaluation formula for calculating the monthly payment is in the starters directory in the file named formula.txt. Note that the interest rate should be specified as a percent rather than a decimal fraction ( e.g., 7.5 rather than .075). Copy  The makePayment function should calculate the monthly interest, subtract the interest from the payment amount, and subtract the remaining amount from the account's balance.  The main function should: • create a 30 year mortgage with a balance of 100,000 at 7.5%; • prompt the user to enter the number of months for which payment is to be made; and • display the payment amount, principal, interest, and balance Trainingfor each month. Centers

Evaluation Copy

©2016 UMBC Training Centers 3-36 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Chapter 4: EvaluationFundamentals of Classes 1) Data Types ...... 4-2

2) User Defined Data Types...... 4-4

3) Using the Class Concept ...... 4-5 4) Defining a Class...... Copy 4-6 5) public and private Access Levels...... 4-9

6) The Scope Resolution Operator ::...... 4-13

7) Using Class Objects Like Built-in Types ...... 4-17

8) Scope...... 4-18

9) Constructors ...... 4-20

10) Member Initialization Lists...... 4-24 11) DestructorTrainings...... Centers 4-26 12) Array of Objects...... 4-30 13) Pointers ...... 4-32

14) The this Pointer...... 4-34

15) Passing Objects to Functions ...... 4-36 16) ReturningEvaluation Objects From Functions ...... 4-38 17) static Class Members...... 4-39 Copy

©2016 UMBC Training Centers 4-1 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Data Types

• Compiler languages give the programmer some fundamentalEvaluation data types. int counter; double salary; string word; Copy • A type implies a:  a specific number of in memory;  an interpretation of those bytes; and  a set of operations on the type.

• Many general-purpose types are built into a programming language. However, you may want some extended types, whichTraining can be used in a wide varietyCenters of your company’s applications. These might include items such as:  Mortgage;  Policy; or  Customer. Evaluation • Good programming languages provide a way to build user created types such as the ones above. In C++, the keywords structCopy and class are used for this purpose. • Creating your own types allows programs to more closely model real world problems, thereby making programs easier to read and maintain.

©2016 UMBC Training Centers 4-2 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Data Types

• User created types should be implemented to satisfy your ownEvaluation corporate IS department needs.

• A user created type should adhere to the principles of encapsulation Copyand data hiding. Remember that:  the coupling of data and functions is called encapsulation; and  data hiding is the prevention of direct access of encapsulated data.

• We will see the benefits of these principles as we continue through the course. Training Centers

Evaluation Copy

©2016 UMBC Training Centers 4-3 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

User Defined Data Types

• A user defined data type is a type together with a set of operations.Evaluation

• Programming with user-defined data types is easier when these types can be used with the ease of the built-in types. As you shallCopy see, this can make the creation of these new data types very difficult.

• An int is a good example of a data type. This data type has certain operations defined for it. + - * / % • However, suppose we need a Mortgage as a data type. What operations are appropriate for it?

• WhenTraining you are creating a new dataCenters type, many questions must be answered.

 Representation – How is the data for this type modeled? Do you use separate elements, an Array, a List, …?  Implementation – How is the data type implemented? What Evaluationalgorithms do you use in implementing the functionality for this type?  Interface – What operations are allowed or disallowed, and how do you invokeCopy them?

©2016 UMBC Training Centers 4-4 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Using the Class Concept • TheEvaluation C++ programmer uses either the class keyword or the struct keyword to implement a user defined data type. • A class (or structCopy) lets you keep the details of a type (its representation and implementation), separate from its interface.  Users are presented with a public interface to a private representation and implementation.

• Therefore, implementations can be altered by the developer of a class without affecting the uses of a class.

 Users of a class need only understand the interface.  User code cannot alter implementation of the methods of a class.Training Centers  Debugging is localized.

 EvaluationClasses can be reused. Copy

©2016 UMBC Training Centers 4-5 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Defining a Class • TheEvaluation class (or struct) keyword is used to create a new data type.

• A class definition must be specified, and then instances (objects) of thatCopy class can be defined. • To illustrate the principles that are involved in building new data types, we will now create the Loan data type.

• A Loan will contain a name, an amount, a number of years, and an interest rate.

• First, we package these data items into a struct. struct Loan {Training Centers string name; double amount, rate; int years; }; • DoEvaluation not forget the semicolon after the closing curly brace! Copy

©2016 UMBC Training Centers 4-6 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Defining a Class

• We have seen the data, and now we have to add the functions.Evaluation Once we have added these functions, we can use this data type in a program like the one below. 4-7.cpp 1. #include Copy 2. #include 3. 4. using namespace std; 5. 6. struct Loan 7. { 8. string name; 9. double amount, rate; 10. int years; 11. 12. string getName() 13. { 14. return name; 15. } 16. Training Centers 17. double getAmount() 18. { 19. return amount; 20. } 21. 22. int getYears() 23. { 24. Evaluation return years; 25. } 26. 27. double getRate() 28. { 29. return rate; 30. } 31. Copy 32. void setName(string n) 33. { 34. name = n; 35. } 36.

©2016 UMBC Training Centers 4-7 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Defining a Class 4-7.cpp (continued) 37. Evaluation void setAmount(double a) 38. { 39. amount = a; 40. } 41. 42. void setYears(int y) 43. { Copy 44. years = y; 45. } 46. 47. void setRate(double r) 48. { 49. rate = r; 50. } 51. }; 52. 53. int main() 54. { 55. Loan myLoan; 56. 57. myLoan.setName("michael"); 58. Training myLoan.setYears(30); Centers 59. myLoan.setAmount(100000); 60. myLoan.setRate(8); 61. 62. cout << myLoan.getName() << " "; 63. cout << myLoan.getAmount() << " "; 64. cout << myLoan.getRate() << " "; 65. cout << myLoan.getYears() << endl; 66. Evaluation 67. return 0; 68. } Copy

©2016 UMBC Training Centers 4-8 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

public and private Access Levels • 4-7.cppEvaluation exhibits sound software engineering practice because it uses the public interface to get and set data. However, the Loan class is not yet industrial strength. The way it is currently defined, a programmer could have accessed the dataCopy directly. Loan myLoan;

myLoan.name = "michael"; myLoan.years = 30; myLoan.amount = 100000; myLoan.rate = 8;

cout << myLoan.name << " "; cout << myLoan.amount << " "; cout << myLoan.rate << " "; cout << myLoan.years << endl;

• Training Centers The code above takes advantage of knowing how the data is represented. This is less than ideal. If the representation of the data were to change, then any program written like this would not compile.

• AccessEvaluation to data can be prevented by taking advantage of the C++ access levels. Typically, we would like to make the data private while keeping the functions public. This is not a mandate. It is simply what works best most of the time. (However,Copy there are some occasions when a function is made private, as we shall see throughout the course.)

©2016 UMBC Training Centers 4-9 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

public and private Access Levels • TheEvaluation set of public functions is referred to as the public interface.

• The public keyword specifies which members can be accessed by usersCopy of the class. • The private keyword specifies that access to these items is limited to the functions of the class itself and not to users of the class.

• When you use a struct, all members of the struct are public by default.

• When you use a class, all members of the class are privateTraining by default. Centers

• This is the only difference between class and struct, although typically C++ programmers always use the classEvaluation keyword to define their new data types. • There can be several public and private sections in a class definition. Their order is irrelevant, and only one section of each Copyis necessary.

©2016 UMBC Training Centers 4-10 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

public and private Access Levels • UsingEvaluation class, public, and private, here is a skeleton view of a new version of the Loan class. class Loan { private: string name;Copy double amount, rate; int years;

public: string getName() { return name; }

double getAmount() { return amount; Training} Centers

int getYears() { return years; }

Evaluation ... };

• With this new organization, any direct references to the data (or any otherCopy private members) are flagged by the compiler.

©2016 UMBC Training Centers 4-11 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

public and private Access Levels • TheEvaluation organization of the program above is not too useful. Ideally, we would like to separate a class definition from any program that uses it. • A better approachCopy is to define a header file, say Loan.h, that consists of data and interface information. Then, define the functions that conform to that interface in another file.

• This separation is shown next. Training Centers

Evaluation Copy

©2016 UMBC Training Centers 4-12 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

The Scope Resolution Operator :: • A normalEvaluation application would include several files.  The application itself  A header (.h) file for each class used by the application. The header file contains the definition of the class (the class body).  A .cpp file for Copyeach class. The .cpp file contains the definitions of the member functions declared in the class body. • Here is the header file. Loan.h

1. #include 2. 3. using namespace std; 4. 5. class Loan 6. { 7. Trainingprivate: Centers 8. string name; 9. double amount, rate; 10. int years; 11. 12. public: 13. string getName(); 14. double getAmount(); 15. int getYears(); 16. Evaluation double getRate(); 17. 18. void setName(string n); 19. void setAmount(double a); 20. void setYears(int y); 21. void setRate(double r); 22. }; Copy

©2016 UMBC Training Centers 4-13 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

The Scope Resolution Operator :: • HereEvaluation is the functions file. Loan.cpp

1. #include 2. using namespace std; 3. 4. #include "Loan.h"Copy 5. 6. string Loan::getName() 7. { 8. return name; 9. } 10. double Loan::getAmount() 11. { 12. return amount; 13. } 14. int Loan::getYears() 15. { 16. return years; 17. } 18. double Loan::getRate() 19. Training{ Centers 20. return rate; 21. } 22. 23. void Loan::setName(string n) 24. { 25. name = n; 26. } 27. Evaluationvoid Loan::setAmount(double a) 28. { 29. amount = a; 30. } 31. void Loan::setYears(int y) 32. { 33. years = y;Copy 34. } 35. void Loan::setRate(double r) 36. { 37. rate = r; 38. }

©2016 UMBC Training Centers 4-14 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

The Scope Resolution Operator :: • SinceEvaluation the two files (the application file and the functions file) are now going to be compiled separately and linked together, the compiler must be able to discern to which class a function belongs.

• This is accomplishedCopy using the scope resolution operator (::). void Loan::setYears(int y) { years = y; }

• The double colon in the code above means that the setYears function belongs to the class Loan. You will see this notation often in compiler diagnostics. For example,Training if you call a function thatCenters the compiler cannot find:

Loan myLoan; myLoan.setLoan("mike", 10000);

TheEvaluation error message may say something like this. cannot find Loan::setLoan(string, int); Copy

©2016 UMBC Training Centers 4-15 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

The Scope Resolution Operator :: • ThereEvaluation may be times when you need to send an object to a non-member function. For example, suppose you wish to write a function that prints all the data items of a Loan. • You could writeCopy a displayLoan function that hides the details of all the function calls necessary to display the Loan object. This function uses the public interface of the Loan class.

4-16.cpp

1. #include 2. 3. using namespace std; 4. 5. #include "Loan.h" 6. 7. Trainingvoid displayLoan(Loan & loan); Centers 8. 9. int main() 10. { 11. Loan myLoan; 12. 13. myLoan.setName("michael"); 14. myLoan.setYears(30); 15. myLoan.setAmount(100000); 16. Evaluation myLoan.setRate(8); 17. displayLoan(myLoan); 18. 19. return 0; 20. } 21. 22. void displayLoan(LoanCopy & loan) 23. { 24. cout << loan.getName() << " "; 25. cout << loan.getAmount() << " "; 26. cout << loan.getRate() << " "; 27. cout << loan.getYears() << endl; 28. }

©2016 UMBC Training Centers 4-16 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Using Class Objects Like Built-in Types • If weEvaluation passed the Loan object to the displayLoan function, then all the values in the object would be copied to the parameter. This, of course, is the familiar pass by value.

• For efficiency, weCopy passed by reference. We should pass by const & but there a few things we do not know yet about passing that way. Therefore, we will defer that topic for a while.

• The successful use of a class depends on how much functionality is built into it and how easy it is to use objects of the class.

• Class writers should strive to make class objects as easy to useTraining as the built-in types. In particular,Centers we would want to use class objects in the following ways.

 Definitions Loan myLoan, yourLoan; // Define a few Loan cashLoan = myLoan; // Initialize one LoanEvaluation loans[7]; // Array of Loans Loan *pt; // Loan pointer

 Prototypes void displayLoan(Loan); // pass a Loan void printLoan(LoanCopy *); // pass a pointer void printLoan(Loan &); // pass reference Loan getLoan(void ); // Return a Loan

©2016 UMBC Training Centers 4-17 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Scope

• Scope refers to that portion of a program where a named itemEvaluation can be accessed.

• If an item has block scope, then it can be accessed only inside of the block where it is defined. Keep in mind that a block itself is definedCopy by a set of curly braces, { }. fun( ) { int x = 1; // function

for (int i = 0; i < 3; i++) // for loop { int r = i; // block .... }

int p = 5; // function { Training int k = p; Centers // block } } • In the above example:  x and p have function block scope;  Evaluationi has for loop block scope; and  r and k has block scope. Copy

©2016 UMBC Training Centers 4-18 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Scope

• File scope refers to a name declared outside of all blocks andEvaluation classes.

• Class scope refers to both data and functions of classes. When inside a member function, all members are directly accessible. Copy

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 4-19 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Constructors • WhenEvaluation we created our Loan objects, the values of the object data within them were unknown. Loan myLoan; cout << myLoan.getAmount(); // ??? Copy • We had to use a series of set functions to give legitimate values to the instance data for Loan objects.

• It would have been easier to give a set of initializers with the creation of an object. Loan myLoan("Mike", 30, 100000, 8); • Whenever you create an object, C++ calls a special function for you. This function is known as a constructor.  TrainingIf you do not provide a constructor, Centers then C++ will provide a default constructor for you. Its behavior is to allocate storage for the data items. However, the contents of these data items are random.

• A constructor is similar to other class function except that a constructor:Evaluation  must have same name as the class name;  cannot have a return type – not even void;  cannot return aCopy value; and  cannot be invoked explicitly.

©2016 UMBC Training Centers 4-20 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Constructors

• A constructor is called automatically upon object creation. Evaluationnew This is true when objects are created using operator as well. A class normally has more than one constructor. Here is an example from the Loan class.

• CopyLoan First, we modify the header file. class Loan { private: string name; double amount, rate; int years;

public: Loan(string n, int y, double a,double r); Loan(string n, int y, double a); TrainingLoan(string n, int y); Centers

string getName(); double getAmount(); int getYears(); double getRate();

Evaluation void setName(string n); void setAmount(double a); void setYears(int y); void setRate(double r); }; Copy

©2016 UMBC Training Centers 4-21 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Constructors • Next,Evaluation we add the following functions to the Loan functions file. Loan::Loan(string n, int y, double amt, double r) { name = n; years = y;Copy amount = amt; rate = r; }

Loan::Loan(string n, int yrs, double amt) { name = n; years = yrs; amount = amt; rate = 7.5; }

Loan::Loan(stringTraining n, int yrs)Centers { name = n; years = yrs; amount = 100000; rate = 7.5; } Evaluation • Given the constructors above, there would be three ways to create a Loan object. Loan myLoan1("michael",Copy 30, 100000, 8.0);

Loan myLoan2("susan", 20, 75000);

Loan myLoan3("erin", 10);

©2016 UMBC Training Centers 4-22 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Constructors • If youEvaluation try to create a Loan object in the following way, a compiler error would be issued. Loan myLoan3;

• However, as youCopy will see, all classes should always provide a default constructor (i.e., a constructor with no arguments). 4-23.cpp

1. #include 2. using namespace std; 3. 4. #include "Loan.h" 5. 6. int main() 7. { 8. Loan myLoan1("michael", 30, 100000, 8.0); 9. Training cout << myLoan1.getName() Centers << " "; 10. cout << myLoan1.getAmount() << " "; 11. ... 12. 13. Loan myLoan2("susan", 20, 75000); 14. cout << myLoan2.getName() << " "; 15. cout << myLoan2.getAmount() << " "; 16. ... 17. 18. Evaluation Loan myLoan3("erin", 10); 19. cout << myLoan3.getName() << " "; 20. cout << myLoan3.getAmount() << " "; 21. ... 22. 23. Loan myLoan4; 24. cout << CopymyLoan4.getName() << " "; 25. cout << myLoan4.getAmount() << " "; 26. ... 27. 28. return 0; 29. }

©2016 UMBC Training Centers 4-23 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Member Initialization Lists

• Object construction proceeds in two phases: the initializationEvaluation phase and the assignment phase.  In certain cases, data members of objects must be satisfied in the initialization phase rather than the assignment phase. • Copy For example, both constants and references must be initialized at the time in which storage is allocated for them.

 Therefore, if a class has data members that are constants or references, they must receive their values during the initialization phase rather than during the assignment phase of construction.

• A member initialization list (a list of member names, argument pairs), is used by a constructor to initializeTraining those data members thatCenters require initialization. The list is preceded by the colon .

• Suppose we have a Record class whose data items are as follows. Evaluationclass Record { private: string name; int & number; const int entry; Copy public: Record(string, int &, int); .... };

©2016 UMBC Training Centers 4-24 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Member Initialization Lists • TheEvaluation constructor for Record would be as follows. Record::Record(string nm, int & nb, int e) : number(nb), entry(e) { name = nm; } Copy • The following would cause two compiler errors. Record::Record(string nm, int & nb, int e) { number = nb; // error entry = e; // error name = nm; }

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 4-25 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Destructors

• A constructor's job is to make certain that an object is createdEvaluation in a "well formed" way. When an object is modeling a complex software component, the behavior of any constructor may likewise become more complex. A constructor mightCopy do the following.  allocate memory  open a file  open a network connection

• Since a constructor executes automatically, there must be an automatic way of undoing the work of the constructor. This is the task of the destructor function.

• A destructor is a member function whose name must bearTraining the name of the class prefixed Centers with the ~ character.  The destructor is automatically called when an object goes out of scope or when the operator delete is applied to a pointer to an object. • A constructorEvaluation is usually overloaded because objects can be created in different ways. However, there can be only one destructor inCopy a class.

©2016 UMBC Training Centers 4-26 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Destructors • In Evaluationthe Loan class, the destructor does not have any real work to do because the constructor does not claim any resources such as memory or a file. Nevertheless, it is instructive to see how it is written and when it is executed.

• When you are developingCopy your classes, it is a good debugging tool to print something from your constructors and from your destructor to get an idea about when these functions are called.

• In order to show you a simple example that illustrates the places where constructor and destructor calls occur, we develop a small test class. Training Centers

Evaluation Copy

©2016 UMBC Training Centers 4-27 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Destructors 4-28.cpp 1. Evaluation#include 2. #include 3. using namespace std; 4. 5. class Test 6. { 7. private: Copy 8. string value; 9. 10. public: 11. Test() 12. { 13. value = "empty"; 14. cout << value << endl; 15. } 16. Test(char * v) 17. { 18. value = v; 19. cout << "creating "<< value << endl; 20. } 21. ~Test() 22. Training { Centers 23. cout << "destroying " << value << endl; 24. } 25. }; 26. 27. void fun2() 28. { 29. cout << "inside fun2()" << endl; 30. Evaluation Test t4("four"); 31. cout << "leaving fun2()" << endl; 32. } 33. 34. void fun1() 35. { 36. cout << "insideCopy fun1()" << endl; 37. Test t3("three"); 38. cout << "calling fun2()" << endl; 39. fun2(); 40. cout << "leaving fun1()" << endl; 41. }

©2016 UMBC Training Centers 4-28 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Destructors 4-28.cpp (continued) 42. Evaluationint main() 43. { 44. Test t1("one"), t2("two"); 45. cout << "calling fun1()" << endl; 46. fun1(); 47. Test *pt = new Test("five"); 48. return 0;Copy 49. }

• Output creating one creating two calling fun1() inside fun1() creating three calling fun2() inside fun2() creating four leavingTraining fun2() Centers destroying four leaving fun1() destroying three creating five destroying two destroying one

• Evaluation Notice that when an object leaves scope, the destructor for that object is automatically called. Also, notice that destructors are called in the opposite order from which the corresponding constructorsCopy are called. • Finally, notice that when new is used, you must use a delete operator in order for the destructor to be called for that object. Since this was not done above, the destructor was never called for the last object in main.

©2016 UMBC Training Centers 4-29 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Array of Objects

• An object has the same status as a built-in type. In particular,Evaluation arrays of objects and pointers to objects can be created.

• An array of objects that is not initialized requires a default constructor. If weCopy use the preceding Test class, then the following array will call the default constructor three times. Test objects[3];

• When these objects go out of scope, the destructor will also be called three times.

• If you wish to initialize an array, the nature of the initialization depends upon the number of arguments the constructorTraining can take. Centers • If you are using the one argument constructor, then you can use the short or the long form of initialization. The short form is: Test objects[3] = { "one", "two", "three" }; Evaluation and the long form is: Test objects[3] = { Test("one"),Copy Test("two"), Test("three") };

©2016 UMBC Training Centers 4-30 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Array of Objects

• If you need to use constructors that require more than one argument,Evaluation you must use the long form of the constructor. Loan loans[] = { Loan("mike", 30, 100000, 8.0), Loan("susan", 20, 75000), Loan ("erin", 10) Copy };

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 4-31 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Pointers

• You can create pointers to objects. These pointers behaveEvaluation exactly the way that C pointers behave (i.e., you can do pointer arithmetic on them; you can point to function members with them, etc.). Loan myLoan("mike", 30, 100000, 8.0); Loan * pt; Copy

pt = &myLoan; double amt = pt -> getAmount();

amt = pt -> amount; // error

• The last line above will cause an error because the object data, amount, is not accessible. It is private and, as usual, you must go through the public interface.

• YouTraining can step through an array Centersof objects either with indices or with pointers. The following example shows

both ways. Evaluation Copy

©2016 UMBC Training Centers 4-32 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Pointers 4-33.cpp 1. Evaluation#include 2. using namespace std; 3. 4. #include "Loan.h" 5. 6. double sumLoans(Loan *loans, int howmany); 7. double avgInterest(LoanCopy *loans, int howmany); 8. 9. int main() 10. { 11. Loan loans[] = { Loan("mike", 30, 100000, 8.0), 12. Loan("susan", 20, 75000), 13. Loan("erin", 10) 14. }; 15. double total, avg; 16. 17. total = sumLoans(loans, 3); 18. cout << "loan total: "<< total << endl; 19. 20. avg = avgInterest(loans, 3); 21. cout << "avg rate: " << avg << endl; 22. Training Centers 23. return 0; 24. } 25. 26. double sumLoans(Loan *loans, int howmany) 27. { 28. double total = 0; 29. for (int i = 0; i < howmany; i++) 30. Evaluation total += loans[i].getAmount(); 31. 32. return total; 33. } 34. 35. double avgInterest(Loan *loans, int n) 36. { Copy 37. double avg = 0.0; 38. for (Loan *p = loans; p < loans + n; p++) 39. avg += p -> getRate(); 40. 41. return avg/n; 42. }

©2016 UMBC Training Centers 4-33 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

The this Pointer • WhenEvaluation a member function is invoked, the invocation is connected to a particular object. The compiler "secretly" passes to the function the address of this object. The address is available through the this pointer. • Copy Here is a diagram to depict this situation. Loan myLoan("susan", 20, 75000);

myLoan Susan 20 75000 7.5

myLoan.getAmount(); myLoan this Training CentersSusan 20 75000 7.5 • Inside the function, you can use this to access the instance data of myLoan. The function can be written as:Evaluation double Loan::getAmount() { return this -> amount; } Copy • If you omit the word this, it is implied. Therefore, in the example, it was not necessary to use this. However, there are many cases where it is necessary. Sometimes it is simply convenient.

©2016 UMBC Training Centers 4-34 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

The this Pointer • HereEvaluation is a version of Fraction::divide that was given as a lab solution at the end of Chapter 3. Fraction divide(Fraction x) { Fraction temp = x; temp.recip();Copy Fraction temp2; temp2.numer = numer; temp2.denom = denom; return temp2.mult(temp); }

• An easier way of writing this function is shown here. Fraction divide(Fraction x) { Fraction temp = x; Trainingtemp.recip(); Centers return (*this).mult(temp); }

• Since this is a pointer to the object on which a member function is called, then *this is the entire object and is appropriateEvaluation as the implied argument to mult. So, the last line above could simply be: return mult(temp);Copy

©2016 UMBC Training Centers 4-35 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Passing Objects to Functions

• Whenever an object is passed to a function by value, a copyEvaluation of the object is constructed to form the parameter.

• A special constructor, the copy constructor, is executed to perform this action. The copy constructor is a different constructor thanCopy any that we have seen so far.

• If your class does not supply this copy constructor, then the compiler supplies one.

 The behavior of the compiler supplied copy constructor is to copy elements on a bit by bit basis into the object being constructed.  This may not be the behavior that you desire, so you may have to write your own copy constructor. We will show how to write oneTraining in the next chapter. Centers • The following code demonstrates an example of where the copy constructor would be invoked. #include "Loan.h"

void process(Loan param) { Evaluation // do something }

int main( ) { Copy Loan myLoan("susan", 20, 75000); process(myLoan); // copy constructor }

©2016 UMBC Training Centers 4-36 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Passing Objects to Functions

• When a function terminates, local variables and parametersEvaluation are popped off the stack. If any of these are objects, the destructor is invoked for each one of them.

• If you have relied on the default copy constructor, then this destructor callCopy could have a nefarious effect on your program. Although we have yet to see this, the problem is prone to arise when at least one class data member is a pointer.

• The problem can be overcome by passing a reference to the object rather than the object itself. #include "Loan.h"

void process(Loan & param) { Training Centers // do something }

int main( ) { Loan myLoan("susan", 20, 75000); Evaluation process(myLoan); // pass by ref }

• Passing a reference is also more efficient than passing by value. Copy

©2016 UMBC Training Centers 4-37 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Returning Objects From Functions

• A similar problem occurs when an object is returned from a function.Evaluation

• The copy constructor copies the returned object back to the caller. The Copylocal object is then destroyed. • This problem can sometimes be solved by returning a reference. In this case, you must make sure that the reference that is returned is not a reference to a local variable.

 For example, the function below must return an object and not a reference to one because the reference will have been destroyed once the function has completed.

FractionTraining Fraction::mult(const Centers Fraction & f) { Fraction temp; // // fill temp with appropriate values // return temp; } Evaluation Copy

©2016 UMBC Training Centers 4-38 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

static Class Members • EachEvaluation object has its own data members. These data members are sometimes called instance data.

• A class can also have data. The static keyword is used for this purpose.Copy static  A member variable is class data.  For each static member variable, there is one sharable copy per class.

• Because static data members are never a part of an object, storage is not allocated for them when an object is created. Therefore, you must take special care of static member variables and define them outside of the classTraining definition. Centers • To ease the burden on users of your class, define these variables in the functions file.

• static members exist in the class scope and obey the accessEvaluation rules with respect to public and private. • static functionsCopy may also be defined.

©2016 UMBC Training Centers 4-39 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

static Class Members • TheEvaluation code below illustrates a nice use for static members. 4-40.cpp

1. #include 2. #include 3. using namespaceCopy std; 4. 5. class ID 6. { 7. private: 8. static int id; 9. int number; 10. string name; 11. 12. public: 13. ID(string param) 14. { 15. number = id++; 16. name = param; 17. Training } Centers 18. static int nextID() { return id; } 19. int getID() { return number; } 20. string getName() { return name; } 21. }; 22. 23. int ID::id = 1; 24. 25. int main() 26. Evaluation{ 27. ID emp[] = { ID("mike"), ID("sue"), ID("erin") }; 28. for (int i = 0; i < 3; i++) 29. { 30. cout << emp[i].getName() << ": "; 31. cout << emp[i].getID() << endl; 32. } Copy 33. cout << "next ID: " << ID::nextID() << endl; 34. 35. return 0; 36. }

©2016 UMBC Training Centers 4-40 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

static Class Members • TheEvaluation static variable id must be defined outside the class definition. int ID::id = 1;

• There is only oneCopy shared instance of id regardless of how many ID objects exist. Each time an ID object is allocated, it is given an identification number.

• static functions are invoked on the class, not on an object. ID::nextID()

• Therefore, a static function, such as nextID, only has accessTraining to static data because Centers it does not have a this pointer.

Evaluation Copy

©2016 UMBC Training Centers 4-41 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Exercises

1. WriteEvaluation a MyDate class that represents a day, month, and year. This class should have several functions to construct MyDate objects such as: // dd, mm, yr MyDate md1(25,12,2001); Copy // dd, mm, assume current yy MyDate md2(25,12);

// dd, assume current mm, and yy MyDate md3(25);

// assume current dd, mm, yy MyDate md4;

The class should have functions to get the day, month, and year. It should also have a function to print a MyDate object.Training See the file 4-1.txt inCenters the starters/4-1 directory.

2. Add the following functions to the MyDate class. To complete this problem, the MyDate class must have two static arrays, one for the days of each month and one forEvaluation the string names of the month. A starter file exists for this exercise in the starters directory. string getMonthAsString(); int getDayOfYear();Copy

©2016 UMBC Training Centers 4-42 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

Exercises 3. Define your own String class, MyString, that implementsEvaluation the functionality shown in the program below. int main() { MyString empty; MyString text("hello"); MyString pal("amanaplanacanalpanama");Copy cout << text.getString() << " is "; cout << text.getLength() << " long "; text.reverse(); cout << "The reversed string is "; cout << text.getString() << endl; if ( pal.ispal()) { cout << pal.getString() << " is "; cout << "a palindrome " << endl; } return 0; } Training Centers Use the following representation for your string. class MyString { private: char * data; int len; Evaluationpublic: … …

4. Add a few static integers to the MyString class. One of them shouldCopy keep track of the number of MyString objects, and the other should keep track of the length of the longest string. Be sure to write two static functions to return these values.

©2016 UMBC Training Centers 4-43 C++ PROGRAMMING CHAPTER 4: FUNDAMENTALS OF CLASSES

EvaluationThis Page Intentionally Left Blank Copy

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 4-44 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Chapter 5: EvaluationOperator Overloading 1) Introduction...... 5-2

2) Rules for Operator Overloading...... 5-3

3) Rationale for Operator Overloading...... 5-4 4) Overloading MemberCopy Functions...... 5-5 5) Overloading Non-Member Functions ...... 5-10

6) friend Functions ...... 5-12

7) The Copy Constructor...... 5-15

8) The Assignment Operator...... 5-22

9) Overloading [ ]...... 5-28

10) Overloading Increment and Decrement Operators...... 5-29 11) constTraining Objects and References ...... Centers 5-30

Evaluation Copy

©2016 UMBC Training Centers 5-1 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Introduction

• Many languages routinely overload operators for the built- in Evaluationtypes. + / * -

int float double Copy • To add flexibility and friendliness to user-defined types, the class designer can overload most of the C++ operators to give new meanings to these operators on a class specific basis.

• When the designer of a class allows operator overloading, it should be done in an intuitive way so that users of the class will not be in for any surprises. Fraction a, b, c; a =Training b + c * d; // naturalCenters a = c << b; // meaningless

String d,e,f; d = e + f; // natural d = e * 2; // natural d Evaluation= e * f // meaningless

Copy

©2016 UMBC Training Centers 5-2 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Rules for Operator Overloading

• Before looking at some examples of overloading operators,Evaluation we need to look at some of the rules provided by the language. Not all operators can be overloaded. In particular, none of the following can be overloaded. . :: .* ?: Copy • No new operator symbols can be created. For example, you cannot define ** to be exponentiation. Likewise, you cannot define <> to mean inequality.

• Any overload must have at least one user-defined type as an operand. Therefore, you cannot change the usual meanings of the built-in operators.

• TheTraining number of operands and theCenters precedence of an operator cannot be altered.

• Overloaded operators are actually functions. Most of them can be either member functions or non-member functions.Evaluation • However, the following operators cannot be overloaded as non-member functions. [ ] = Copy -> • If you overload + and = in any class, this does not mean that you have overloaded +=.

©2016 UMBC Training Centers 5-3 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Rationale for Operator Overloading

• Operator overloading is allowed in C++ to make the use of newEvaluation classes friendlier. To illustrate this, suppose we have a Fraction class with the following functions. class Fraction { private: Copy int numer, denom; public: Fraction(int a = 0, int b = 1); Fraction mult(const Fraction & cfr); Fraction add(const Fraction & cfr); Fraction divide(const Fraction & cfr) Fraction subtract(const Fraction & cfr); … … };

• NowTraining suppose we have the following Centers fractions, and we want to evaluate the expression below.

a = 2/3; b = 5/2 c = 4/3 d = 1/2 Evaluation c = (a – b) * (c + d) • If we use the functions above, we end up with the following, whichCopy is not a pretty sight. c = (a.subtract(b)).mult(c.add(d))

©2016 UMBC Training Centers 5-4 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Overloading Member Functions

• Of course, the code is much clearer if it can be written as follows.Evaluation c = (a – b) * (c + d); • This can be accomplished by overloading the appropriate operators. Copy

• In C++, an overloaded operator is actually a function with a peculiar name. For example, if one wanted to overload the multiply function as a member function, one simply defines a function named: operator*

• The function would look exactly like this. FractionTraining Fraction::operator*(const Centers Fraction& c) { Fraction temp; temp.numer = c.numer * numer; temp.denom = c.denom * denom; return temp; } Evaluation • Strictly speaking, you can execute the above function like any other member function. c = a.operator*(b);Copy

©2016 UMBC Training Centers 5-5 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Overloading Member Functions

• However, this defeats the purpose of writing an operator functionEvaluation in the first place. For operator functions, C++ allows you to use the operator version of the function. Therefore, the following two lines are identical. c = a * b; c = a.operator*(b);Copy • You should realize that operator overloads are really functions. Here is an example of the Fraction class with all of the simple operators overloaded.

Fraction.h

1. class Fraction 2. { 3. private: 4. Training int numer; Centers 5. int denom; 6. 7. public: 8. Fraction(int a = 0, int b = 1); 9. 10. void print(); 11. void recip(); 12. 13.Evaluation Fraction operator*(const Fraction & p);

14. Fraction operator+(const Fraction & p); 15. Fraction operator/(const Fraction & p); 16. Fraction operator-(const Fraction & p); 17. }; Copy

©2016 UMBC Training Centers 5-6 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Overloading Member Functions

Fraction.cppEvaluation 1. #include 2. using namespace std; 3. 4. #include "Fraction.h" 5. 6. Fraction::Fraction(intCopy a, int b) : numer(a), denom(b) {} 7. 8. void Fraction::recip() 9. { 10. int temp = numer; 11. numer = denom; 12. denom = temp; 13. } 14. 15. void Fraction::print( ) 16. { 17. cout << numer << "/" << denom << endl; 18. } 19. 20. Fraction Fraction::operator*(const Fraction& p) 21. Training{ Centers 22. Fraction temp; 23. temp.numer = p.numer * numer;

24. temp.denom = p.denom * denom; 25. return temp; 26. } 27. 28. Fraction Fraction::operator/(const Fraction& p) 29. Evaluation{ 30. Fraction temp = p; 31. temp.recip(); 32. return *this * temp; 33. } 34. 35. Fraction Fraction::operator+(constCopy Fraction& p) 36. { 37. Fraction temp; 38. temp.numer=p.numer*denom+p.denom * numer ; 39. temp.denom = p.denom * denom; 40. return temp; 41. }

©2016 UMBC Training Centers 5-7 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Overloading Member Functions Fraction.cpp (continued) 42. EvaluationFraction Fraction::operator-(const Fraction& p) 43. { 44. Fraction temp = p; 45. temp.numer *= -1; 46. return *this + temp; 47. } Copy

5-8.cpp

1. #include "Fraction.h" 2. 3. int main() 4. { 5. Fraction a(2,3), b(5,2), c(4,3), d(1,2); 6. 7. c = (a - b) * (c + d); 8. c.print(); 9. 10. return 0; 11. Training} Centers

• It is reasonable to combine fractions and other arithmetic types in computations. For example, you may want to writeEvaluation the following. Fraction a(1,2), b(1,3), c; c = a * 2; • You have two choices here. You can overload the operator* functionCopy to take an integer argument. Therefore, you would have two operator* functions, one for ints and one for Fractions. Fraction Fraction::operator*(const Fraction &); Fraction Fraction::operator*(int);

©2016 UMBC Training Centers 5-8 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Overloading Member Functions

• The other choice is, oddly enough, dependent upon the useEvaluation of a constructor as a conversion function. When the compiler does not see a function which exactly matches c = a * 2;

it uses the oneCopy argument Fraction constructor to create a temporary fraction from the integer '2' and then calls the function Fraction*(const Fraction &). Finally, it calls the destructor to destroy the temporary Fraction.

 If you do not have a one-argument Fraction constructor, a compiler error is issued.

• There is another issue. See the expression: c =Training 2 * a; Centers

Keep in mind that the use of operators to call functions is a convenience allowed by the compiler.

 Do not lose sight of the fact that the above expression is an attempt at: Evaluationc = 2.operator*(a);

which, of course, is an error. Only an object can appear to the left of the dot operator. • The only solutionCopy to the above problem is to use an overloaded function that is not a member function.

©2016 UMBC Training Centers 5-9 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Overloading Non-Member Functions • TheEvaluation code for the non-member overloaded operator* function is shown below. Fraction operator*(int x, const Fraction & cf) { Fraction temp; temp.n = cf.nCopy * x; temp.d = cf.d; return temp; }

• The code above can be invoked in either of the following ways. c = operator*(2, a) c = 2 * a;

• Therefore,Training to allow for all of the Centers possibilities, we have mentioned that you may have to code many functions. For the multiply alone we have seen:

// member functions // FractionEvaluation operator*(const Fraction & cf) Fraction operator*(int)

// non-member function // Fraction operator*(intCopy x, const Fraction & cf)

©2016 UMBC Training Centers 5-10 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Overloading Non-Member Functions

• As it turns out, if the proper one argument constructor is available,Evaluation then the following non-member function will handle all of the multiplications we have mentioned. Fraction operator* (const Fraction &, const Fraction &); Copy • That is, the above function handles each of the following. Fraction a, b, c; c = a * b; c = a * 2; c = 2 * a;

• However, since the above function is a non-member function, it has no access to the private data members of aTraining Fraction. This is not a problem,Centers but it is inconvenient. You could always use the following functions to get or set needed parts of fractions. int getNumerator(); int getDenominator(); void setNumerator(int); void setDenominator(int); Evaluation • A more convenient, albeit more controversial, solution is to use a friendCopy function.

©2016 UMBC Training Centers 5-11 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

friend Functions • A friendEvaluation function is simply a non-member function that has access to all of the members of a class.

 One or more functions can be made friends to a single class.  One or more functions can be made a friend to more than one class. Copy  An entire class can be made a friend to another class.

• A non-member function is made a friend function by placing its prototype inside the class definition prefixed with the keyword friend.

• friend functions are simply a convenience, but since they violate the principles of information hiding, they are frownedTraining upon by some organizations. Centers • Use friends with caution. Model your friends after the examples that we use in this course.

• Here is a complete example of a use for friend functionsEvaluation. Copy

©2016 UMBC Training Centers 5-12 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

friend Functions Fraction.h 1. Evaluationclass Fraction 2. { 3. private: 4. int numer; 5. int denom; 6. 7. public: Copy 8. Fraction(int n = 0, int d = 1); 9. 10. void recip(); 11. void print(); 12. 13. friend Fraction operator* 14. (const Fraction & p, const Fraction &); 15. friend Fraction operator/ 16. (const Fraction & p, const Fraction &); 17. };

Fraction.cppTraining (excerpt) Centers 1. #include "Fraction.h" 2. 3. Fraction operator*(const Fraction & p1, 4. const Fraction & p2) 5. { 6. Fraction temp; 7. temp.numer = p1.numer * p2.numer; 8. Evaluation temp.denom = p1.denom * p2.denom; 9. return temp; 10. } 11. 12. Fraction operator/(const Fraction & p1, 13. const Fraction & p2) 14. { Copy 15. Fraction temp = p2; 16. temp.recip(); 17. return temp * p1; 18. }

©2016 UMBC Training Centers 5-13 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

friend Functions 5-14.cpp 1. Evaluation#include 2. 3. using namespace std; 4. 5. #include "Fraction.h" 6. 7. main() Copy 8. { 9. Fraction a(2,3), b(5,6), c; 10. 11. a.print(); 12. b.print(); 13. 14. cout << "MULT" << endl; 15. c = a * b; 16. c.print(); 17. 18. cout << "DIVIDE" << endl; 19. c = a / b; 20. c.print(); 21. 22. Training return 0; Centers 23. }

Evaluation Copy

©2016 UMBC Training Centers 5-14 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Copy Constructor • WhenEvaluation an object is created, a constructor is invoked. Loan myLoan("michael", 30); Loan yourLoan("susan", 25);

• When an objectCopy is copied, a special constructor called the copy constructor is invoked to create the copy. Look carefully at the program on the next page and try to determine when an object is constructed from another object of the same type. When this happens, the copy constructor is invoked.

• Here is the output from the program on the next page.

creating Michael destroying Michael creatingTraining Joel Centers destroying Joel destroying Joel destroying Michael destroying Joel

• It appearsEvaluation that three more objects were destroyed than were constructed. However, that is not possible. What has happened is that the compiler has supplied a copy constructor in every place where a Pair object was created from anotherCopy Pair object. Can you find those places?

©2016 UMBC Training Centers 5-15 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Copy Constructor

5-16.cppEvaluation 1. #include 2. #include 3. 4. using namespace std; 5. 6. class Pair Copy 7. { 8. private: 9. int number; 10. string name; 11. 12. public: 13. Pair(int number, string name) 14. { 15. cout << "creating " << name << endl; 16. this -> number = number; 17. this -> name = name; 18. } 19. 20. ~Pair() 21. Training { Centers 22. cout << "destroying " << name << endl; 23. }

24. }; 25. 26. void fun1(Pair param) { } 27. 28. Pair fun2() 29. Evaluation{ 30. Pair p2(200, "Joel"); 31. return p2; 32. } 33. 34. int main() 35. { Copy 36. Pair p1(100, "Michael"); 37. Pair p2 = p1; 38. fun1(p1); 39. p1 = fun2(); 40. return 0; 41. }

©2016 UMBC Training Centers 5-16 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Copy Constructor • TheEvaluation most obvious place is the line: Pair p2 = p1; • However, there are other places as well.  Each time a PairCopy is sent to a function by value , the copy constructor copies it there. This is the case when we make the following call. fun1(p1);

 If the call was made by reference, then the copy constructor would not be called.

• When an object is returned from a function (unless it is by reference or by a pointer), then the copy constructor is responsible for creating the copy sent back to the caller. PairTraining fun2() Centers { Pair p2(200, "Joel"); return p2; } • There are some cases where you cannot rely on the defaultEvaluation copy constructor. To see why this is the case, notice the series of diagrams supporting the code on the next page. Copy

©2016 UMBC Training Centers 5-17 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Copy Constructor • WeEvaluation first create a simple IntArray class. IntArray.h

1. class IntArray 2. { 3. private: 4. int howmany;Copy 5. int *data; 6. 7. public: 8. IntArray(int size = 10); 9. ~IntArray() 10. void print(); 11. };

IntArray.cpp

1. #include 2. using namespace std; 3. 4. Training#include "IntArray.h" Centers 5. 6. IntArray::IntArray(int size) 7. { 8. howmany = size; 9. data = new int[howmany]; 10. for (int i = 0; i < howmany; i++) 11. data[i] = 0; 12. Evaluation} 13. 14. IntArray::~IntArray() 15. { 16. delete [] data; 17. } 18. 19. void IntArray::print()Copy

20. { 21. for (int i = 0; i< howmany; i++) 22. cout << data[i] << " "; 23. cout << endl; 24. }

©2016 UMBC Training Centers 5-18 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Copy Constructor 5-19.cpp 1. Evaluation#include "IntArray.h" 2. 3. int main() 4. { 5. IntArray values(10); 6. values.print(); 7. Copy 8. IntArray items = values; 9. items = values; 10. 11. return 0; 12. }

• When values is constructed, the resultant storage layout can be depicted as follows.

Training values Centersactual data values

howmany = 10

data Evaluation Copy

©2016 UMBC Training Centers 5-19 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Copy Constructor • WhenEvaluation the items object is constructed, the default copy constructor copies elements of values, bit by bit, into the area for the items object. The resultant is that two pointers are now pointing to the same data. IntArray items = values; Copy values actual data values

howmany = 10

data

items

howmany = 10

data

• Training Centers Now consider what happens when the destructor is called for values. The storage for the data items is released.  This means that when the destructor is called for items, it will try to delete storage that it no longer owns • Evaluation The solution is that the IntArray class must write its own copy constructor and not rely on the compiler’s default. This will be true for every class that has pointers to dynamically allocatedCopy memory.

©2016 UMBC Training Centers 5-20 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Copy Constructor

• When you write a copy constructor, you must pass by constEvaluationIntArray reference. Here is the copy constructor. IntArray(const IntArray & car) { howmany = Copycar.howmany; data = new int[howmany]; for (int i = 0; i < howmany; i++) data[i] = car.data[i]; }

• The copy constructor assures that the new object has its own memory. After copying the howmany element, it allocates new storage and then copies elements to that new storage from the original data. The new picture wouldTraining look like this. Centers values actual data values

howmany = 10

data

items actual data values

Evaluationhowmany = 10

data Copy

©2016 UMBC Training Centers 5-21 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Assignment Operator

• The assignment operator has a similar story to that of theEvaluation copy constructor.

• First, you must understand the difference between assignment and construction because they can appear to look the same. Copy int x = 5; x = 0;

• In the two lines above, the top line is the place where storage is allocated. The initialization of that storage is something that happens with allocation. On the other hand, the second line above assigns the value 0 to the storage, but there is no new allocation there. • Training Centers The same thing is true with objects. In the code below, the second line is construction and initialization while the bottom line is assignment. Only the second line will call the copy constructor. IntArray values(10); IntArrayEvaluation items = values; items = values;

• What is called for the last line above? The compiler has a built-in assignmentCopy operator for objects. Its behavior is similar to the copy constructor (i.e., the assignment proceeds bit by bit). Therefore, if your object data contains a pointer, then you cannot rely on the built-in assignment operator. You must overload it and provide the correct behavior.

©2016 UMBC Training Centers 5-22 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Assignment Operator

• Additionally, the built-in assignment operator causes anotherEvaluation problem that we need to explore. We will look at the picture after two IntArray objects have been constructed. valuesCopy actual data values howmany = 10

data

items actual data values

howmany = 10

data

• Now we will look at the diagram when the default assignmentTraining occurs. Centers items = values;

values actual data values

howmany = 10

Evaluationdata

items actual data values

howmany = 10

data Copy

©2016 UMBC Training Centers 5-23 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Assignment Operator

• We have two problems. Not only do we have two pointers to Evaluationthe same data, causing the same dilemma when the destructor executes, but also there is some memory that is now unrecoverable. C++ programmers call this a memory leak. • Copy To fix the problem, we need to overload the assignment operator.

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 5-24 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Assignment Operator

• Remember that an overloaded operator is really a function.Evaluation In this case the function’s name is: operator=

and its use is either of the following with the latter being preferred. Copy

values.operator=(items); values = items;

• However, C++’s roots are embedded in C and whenever possible we wish to make the use of objects as close as possible to the use of the built-in types in C. In particular, we would also like to use the assignment operator in situations like the ones below. valuesTraining = items = data; Centers if ( values = data) != items) cout << "values and items differ" << endl;

• In each of the cases above, operator= must return its implied left argument. For efficiency, the function will returnEvaluation a reference. Its definition will have the following skeleton. IntArray & operator=(const IntArray & car) { return *this;Copy }

©2016 UMBC Training Centers 5-25 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Assignment Operator • RecallEvaluation that this is a pointer to the object on which the function was called and *this is the actual object.

• The first part of the function guards against an assignment such as: Copy items = items;

• The entire function is shown below.

IntArray & operator=(const IntArray & car) { if ( this != &car ) { delete [] data; howmany = car.howmany; data = new int[howmany]; Training for (int i = 0; i Centers< howmany; i++) data[i] = car.data[i]; }

return *this; } Evaluation • The function is very similar to the copy constructor, except that in this case we must be careful to release storage occupied by the target object before we assign it the new data. Copy

©2016 UMBC Training Centers 5-26 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

The Assignment Operator

• Beginning C++ students sometimes find it difficult to follow whenEvaluation a function returns a reference. Recall that a reference is similar to a self-dereferencing pointer. Therefore, the use of this function does not have to do any of the dereferencing. • Copy The function could have been written to return a pointer. IntArray * operator=(const IntArray & car) { if ( this != &car ) { delete [] data; howmany = car.howmany; data = new int[howmany]; for (int i = 0; i < howmany; i++) data[i] = car.data[i]; } Trainingreturn this; Centers }

• The developer is now stuck with coding as follows. This style of coding for an assignment is much different from the usual coding for an assignment and will be unacceptableEvaluation to users of the class.

*( values = *(items = data) );

if ( *(values = data) ) != items) cout << Copy"values and items differ" << endl;

©2016 UMBC Training Centers 5-27 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Overloading [ ] • OperatorEvaluation [] is usually overloaded as the selection operator for user-defined classes. It also must be written to return a reference to shield the developer from pointer dereferencing notation. • Copy This operator results in a nice abstraction. Users of this operator can code with the relaxed familiarity of array subscript notation even though a function is being called to produce the results. The code below shows the minimal parts of a String class to illustrate []. class String { private: int len; char *data; public: TrainingString(char *s) Centers { len = strlen(s); data = new char[len + 1]; strcpy(data, s); } char & operator[](int pos) Evaluation { return data[pos]; } }; Copy • Any of the following are correct uses of []. String word("very cool"); cout << word[0] << endl; // v word[0] = 'b'; // bery word.operator[](0) = 'e'; // eery

©2016 UMBC Training Centers 5-28 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Overloading Increment and Decrement Operators

• Some classes might want to overload the increment and decrementEvaluation operators in order to provide the convenience that the various int types allow.

• This is a little tricky because the overload of the pre and the post incrementsCopy would look the same, both having the signatures: operator++()

• Early C++ compilers had no way to differentiate between the following. object++ ++object • Ultimately, the following solution was standardized. If you wantedTraining to overload both pre and Centers post increments, your class would define the post increment with a dummy

parameter in the prototype and in the definition. operator++() // pre operator++(int) // post Evaluation Copy

©2016 UMBC Training Centers 5-29 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

const Objects and References • TheEvaluation most prudent way of passing objects to functions is by using the const & type. However, when you use a member function on a parameter of this type, the compiler sometimes issues an error message. For example, examine the functionCopy below. bool IntArray::compare(const IntArray & car) { cout << "comparing "; this -> print(); car.print(); ...... }

• The last line in the function will cause the following error.

'print'Training : cannot convert Centers 'this' pointer from 'const class IntArray' to 'class IntArray &'

Conversion loses qualifiers

• WhenEvaluation you call a function on a const or a const &, the compiler cannot know if that function might attempt to alter the object on which it is called. If you need to use a function on these types, you must assure the compiler whether this function is safe (i.e., will not change the object). We willCopy look at a Fraction class to view the details.

©2016 UMBC Training Centers 5-30 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

const Objects and References

class Fraction Evaluation{ private: int n, d;

public: Fraction(intCopy a = 0, int b = 1); void print() const; void recip(); void setNumerator(int num); int getNumerator() const; void setDenominator(int num); int getDenominator() const; Fraction operator+(const Fraction&) const; Fraction operator*(const Fraction&) const; };

• OnlyTraining those functions that do not Centers change the object are marked as const. These are now safe functions executed against const and const & types.

• If a function is const, you must not only specify this when you declare the function (as above), but also when you defineEvaluation the function. void Fraction::print() const { cout << n << "/" << d << endl; } Copy

©2016 UMBC Training Centers 5-31 C++ PROGRAMMING CHAPTER 5: OPERATOR OVERLOADING

Exercises

1. ImplementEvaluation each of the following functions as non-member friends of the Fraction class. Starter code is available in the starters directory. operator+ operator- Copy 2. Rewrite the copy constructor and the assignment operator for IntArray such that the common parts of those functions are placed in a private function and called from both the copy constructor and the assignment operator. Starter code is available in the starters directory. 3. Provide the necessary additional functions for the IntArray class so that the code below works as describedTraining in the comments. Centers IntArray values(10);

values = 0; // assign 0 to all elements values.reset(1); // assign 1 to all elements ++values; // add 1 to all elements values[0] = 5; // assign 5 to values[0] Evaluation 4. Add an operator+ function to IntArray so that the following is possible. IntArray values(10), items(10); values = valuesCopy + items;

5. Take the MyString class from a previous exercise and add a copy constructor and an assignment operator.

©2016 UMBC Training Centers 5-32 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

Chapter 6: EvaluationComposition of Classes 1) Relationships ...... 6-2

2) Composition of Classes...... 6-3

3) The Point Class...... 6-4

4) The Line Class ...... Copy 6-5

5) Member Initialization Lists...... 6-6

6) An Application With Composition...... 6-7

7) The Copy Constructor Under Composition ...... 6-8

8) operator= Under Composition ...... 6-9

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 6-1 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

Relationships

• In the beginning of this course, we gave a little information aboutEvaluation designing a few classes. One of the steps in the design process is to seek out relationships that may exist between classes.

• While there areCopy many different kinds of relationships, the two most important kinds are composition and inheritance. This chapter deals with composition, while the next chapter deals with inheritance.

• If two classes are related so that one class contains an object from the other, then the containing class exhibits composition.

 Composition models the has-a relationship. • Training Centers There are many examples of this in the real world.  A Car has an Engine.  An Employee has a Hire Date.  EvaluationA Computer has a Disk. • Whenever a class object is composed of other class objects, there are certain issues that must be resolved by the containing class.Copy

©2016 UMBC Training Centers 6-2 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

Composition of Classes

• To illustrate various issues regarding composition, our examplesEvaluation will be of a higher level of complexity because they will be using more than one class.

• If you are using the recommended separation of code into a header file andCopy a functions file for each class, you have to assure that the same file does not get included more than once in any given file.

• To guard against this, the following C-like technique is used. Each class assures that no multiple inclusion of header files occur by using conditional compilation. Each class will look like the following. #ifndef NAME_H #define NAME_H Training Centers class Name {

};

#endif Evaluation • We will be using the classes Point and Line to illustrate the issues regarding composition. A Point object will simply contain an x and a y coordinate. A Line will contain two PointCopy objects.

©2016 UMBC Training Centers 6-3 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

The Point Class • HereEvaluation is the code for the header file and the functions file. Point.h

1. #ifndef POINT_H 2. #define POINT_H 3. 4. class Point Copy 5. { 6. private: 7. int xc, yc; 8. 9. public: 10. Point(int x, int y); 11. Point(const Point & p); 12. void print( ) const; 13. }; 14. 15. #endif

Point.cppTraining Centers 1. #include 2. 3. using namespace std; 4. 5. #include "Point.h" 6. 7. EvaluationPoint::Point(int x, int y) : xc(x), yc(y) 8. {} 9. 10. Point::Point(const Point & p) : xc(p.xc), yc(p.yc) 11. {} 12. 13. void Point::print(Copy ) const 14. { 15. cout << xc << "," << yc << endl; 16. }

©2016 UMBC Training Centers 6-4 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

The Line Class • HereEvaluation is the code for the header file and the functions file. Line.h

1. #ifndef LINE_H 2. #define LINE_H 3. 4. #include "Point.h"Copy 5. 6. class Line 7. { 8. private: 9. Point p1, p2; 10. 11. public: 12. Line(const Point & p1, const Point & p2); 13. void print( ) const; 14. }; 15. 16. #endif

Training Centers Line.cpp 1. #include 2. 3. using namespace std; 4. 5. #include "Line.h" 6. Evaluation 7. Line::Line(const Point & a1, const Point & a2) 8. : p1(a1) , p2(a2) 9. { } 10. 11. void Line::print( ) const 12. { Copy 13. p1.print(); 14. p2.print(); 15. }

©2016 UMBC Training Centers 6-5 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

Member Initialization Lists • SinceEvaluation a Line consists of two Point objects, each Line constructor is responsible for calling a Point constructor for each of its contained Point parts. • A member initializationCopy list is used to invoke the Point constructors. Line::Line(const Point & a1, const Point & a2) : p1(a1) , p2(a2) { } // empty body

• The colon starts the member initialization list. This is followed by the names of each member of this Line object and its respective initializer. In this case, the Point members, p1, and p2, are initialized with the parameters,Training a1 and a2, respectively. Centers • In this particular example, there is no work remaining for the body of the constructor, but the empty body still must be provided.

• If theEvaluation Line constructor does not call a contained object's constructor in the initialization list, the compiler will call the default constructor.

• If there is no defaultCopy constructor, an error is issued.

©2016 UMBC Training Centers 6-6 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

An Application With Composition

• This application requires two header files, two functions filesEvaluation and the application itself. How you compile and link all of these files depends strictly upon the environment and the C++ compiler that you are using.

• Here is a small Copyprogram that uses all of the files mentioned above. 6-7.cpp

1. #include "Point.h" 2. #include "Line.h" 3. 4. int main() 5. { 6. Point p1(0,0), p2(3,4); 7. Line line1(p1, p2); 8. Line line2 = line1; 9. 10. Training line1.print(); Centers 11. line2.print(); 12. 13. line1 = line2; 14. 15. return 0; 16. Evaluation} Copy

©2016 UMBC Training Centers 6-7 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

The Copy Constructor Under Composition

• Recall the copy constructor. Are there any special considerationsEvaluation with composition? Point p1(0,0), p2(3,4); Line segment1(p1,p2);

// copy constructorCopy // Line segment2 = segment1;

• The Line copy constructor should use the member initialization list as any other constructor does to initialize its Point members. If it does not, then the compiler will issue an error unless there is a default constructor in the Point class. • TheTraining Line copy constructor is shownCenters below.

Line::Line(const Line & clr)

: p1(clr.p1), p2(clr.p2) { Evaluation} Copy

©2016 UMBC Training Centers 6-8 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

operator= Under Composition • WhatEvaluation about the assignment operator? Are there any special considerations under composition? Point p1(0,0), p2(3,4); Line segment1(p1,p2); Line segment2(p2,p1); Copy // assignment operator // segment2 = segment1;

• The Line assignment operator is shown below. Line & Line::operator=(const Line & clr) { p1 = clr.p1; p2 = clr.p2;

Training return *this; Centers }

• If the containing class relies on the default operator=, then the operator= from the contained class will be called if it is provided. If it is not provided, then the default operator=Evaluation function will be called by the compiler.

• However, if the containing class has its own operator= function, then it is responsible for calling the contained classes’ operator=Copy function.

©2016 UMBC Training Centers 6-9 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

Exercises

1. UseEvaluation the MyDate class and the MyString class from previous labs to implement an Employee class as shown here. If you do not have these classes, they are available in the starters/6-1 directory. class EmployeeCopy { private: MyDate hiredate; MyString name;

public: Employee(MyString n, MyDate d); MyString getName() const; MyDate getDate() const; void print() const; };

intTraining main() Centers { MyString name("Michael"); MyDate today; Employee candidate(name, today);

candidate.print(); Evaluation return 0; }

2. Now create a Company class, which contains an array of Employees, anCopy inception date of type MyDate , and a MyString object for the name of the company. Starter code for this exercise can be seen on the following pages and is available in the starters/6-2 directory.

©2016 UMBC Training Centers 6-10 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

Exercises Company.h 1. Evaluation// 2. // Starter code for Exercise 6-2 3. // 4. 5. #ifndef COMPANY_H 6. #define COMPANY_H 7. Copy 8. #include "MyDate.h" 9. #include "MyString.h" 10. #include "Employee.h" 11. 12. class Company 13. { 14. private: 15. MyDate inception; 16. MyString companyName; 17. Employee **workers; 18. int numPeople; 19. int capacity; 20. 21. public: 22. Training Company(MyDate date, MyStringCenters name, int howmany); 23. 24. const char * getCompanyName() const; 25. int companySize() const; 26. 27. void showInceptionDate() const; 28. 29. Employee *getEmployee(MyString name); 30. Evaluation void addEmployee(Employee & emp); 31. 32. void printWorkers() const; 33. }; 34. 35. #endif Copy

©2016 UMBC Training Centers 6-11 C++ PROGRAMMING CHAPTER 6: COMPOSITION OF CLASSES

Exercises 6-2.cpp 1. Evaluation// 2. // Starter code for Exercise 6-2 3. // 4. #include 5. 6. using namespace std; 7. Copy 8. #include "MyDate.h" 9. #include "MyString.h" 10. #include "Employee.h" 11. #include "Company.h" 12. 13. int main() 14. { 15. MyDate today; 16. Company company(today, "/training/etc", 5); 17. 18. cout << company.getCompanyName() << endl; 19. company.showInceptionDate(); 20. cout << "SIZE: " << company.companySize() << endl; 21. company.printWorkers(); 22. Training Centers 23. MyString ms1("mike"); 24. MyString ms2("susan"); 25. MyString ms3("erin"); 26. Employee e1(ms1, today); 27. Employee e2(ms2, today); 28. Employee e3(ms3, today); 29. 30. Evaluation company.addEmployee(e1); 31. company.addEmployee(e2); 32. company.addEmployee(e3); 33. 34. cout << "SIZE: " << company.companySize() << endl; 35. company.printWorkers(); 36. Copy 37. (*company.getEmployee(ms1)).print(); 38. 39. return 0; 40. }

©2016 UMBC Training Centers 6-12 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Chapter 7: EvaluationInheritance 1) Introduction...... 7-2

2) Public Base Classes ...... 7-4

3) The protected Access Level...... 7-9

4) Member InitializationCopy Lists...... 7-11 5) What Isn’t Inherited...... 7-15

6) Assignments Between Base and Derived Objects ...... 7-16

7) Compile-Time vs. Run-Time Binding ...... 7-18

8) virtual Functions...... 7-21

9) Polymorphism ...... 7-27

10) virtual Destructors...... 7-28 11) PureTraining virtual Functions...... Centers 7-29 12) Abstract Base Classes ...... 7-31 13) An Extended Inheritance Example ...... 7-32 Evaluation Copy

©2016 UMBC Training Centers 7-1 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Introduction

• Object-oriented languages generally share three characteristics.Evaluation  encapsulation  inheritance  polymorphism Copy

• Encapsulation couples functions and data as a single entity.

• Polymorphism (many forms) refers to the same message invoking a different method. There are different forms of polymorphism. int a,b,c; double x,y,z; Training Centers c = a + b; // operator overloading x = y + z;

print(a); // function overloading print(x); Evaluation • Inheritance gives the capability of reusing software by specializing existiCopyng general solutions.

©2016 UMBC Training Centers 7-2 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Introduction

• Languages that support inheritance provide a way of creatingEvaluation type - subtype relationships.

• An existing class can be a generalization for a more specialized class.Copy class Vehicles; // general class Cars; // specific class Trucks; // specific

• Classes that are more specialized can be derived from the general class.

• Functions and data from the general classes are inherited by the specialized classes. This leads directly to code reuse.Training Centers • The specialized class will normally add functions and/or data to support the specialization. • LargeEvaluation class hierarchies can be built. • In C++, the general class is called the base class and the specialized class is called the derived class. Note that base and derivedCopy are not C++ keywords.

©2016 UMBC Training Centers 7-3 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Public Base Classes

• Modeling a derived class as a specialization of a base classEvaluation is often called the is-a relationship. To specify that one class be derived from another, the following notation is used. class Loan { Copy ...... };

class BusinessLoan : public Loan { ...... };

 Loan is the base class; BusinessLoan is the derived class. classTraining Airplane { Centers ...... };

class DC10: public Airplane { ... Evaluation ... };

 Airplane is the base class; DC10 is the derived class. • Copy public specifies that public inheritance is being used. This form of inheritance is used to model the is-a relationship. Although C++ also allows private and protected inheritance, these are rarely used.

©2016 UMBC Training Centers 7-4 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Public Base Classes • RecallEvaluation the Loan class. There are many different loan types on the market. There are business loans, car loans, and home mortgage loans. Each of these is-a special type of loan. Therefore, each can be derived from Loan. Here is the Loan.hCopy file with header guards. Loan.h

1. #ifndef LOAN_H 2. #define LOAN_H 3. 4. #include 5. using namespace std; 6. 7. class Loan 8. { 9. private: 10. string name; 11. double amount, rate; 12. int years; 13. Training Centers 14. public: 15. Loan(string n, int yrs, double amt, double r); 16. Loan(string n, int yrs, double amt); 17. Loan(string n, int yrs); 18. 19. // Loan() { } Explanation to follow 20. 21. Evaluation string getName(); 22. double getAmount(); 23. int getYears(); 24. double getRate(); 25. 26. void setName(string n); 27. void setAmount(doubleCopy a); 28. void setYears(int y); 29. void setRate(double r); 30. }; 31. 32. #endif

©2016 UMBC Training Centers 7-5 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Public Base Classes • ToEvaluation derive Mortgage from Loan, we write the following. Mortgage.h

1. #ifndef MORTGAGE_H 2. #define MORTGAGE_H 3. 4. #include Copy 5. using namespace std; 6. 7. class Mortgage : public Loan 8. { 9. private: 10. double payment; 11. double balance; 12. double principal; 13. double interest; 14. double computePayment(); 15. 16. public: 17. Mortgage(string n, int yrs, double amt, double r); 18. 19. Training double getPayment(); Centers 20. void makePayment(); 21. double getBalance(); 22. double getPrincipal(); 23. double getInterest(); 24. }; 25. 26. Evaluation#endif • A Mortgage is a Loan. Therefore, Mortgage objects have use of all (non-constructor) Loan functions in addition to the Mortgage functions. This is a good example of codeCopy reuse, one of the major benefits of inheritance.

• The file where Mortgage functions are implemented is shown on the following page.

©2016 UMBC Training Centers 7-6 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Public Base Classes

Mortgage.cppEvaluation 1. #include 2. #include 3. 4. using namespace std; 5. 6. #include "Loan.h"Copy 7. #include "Mortgage.h" 8. 9. Mortgage::Mortgage(string name, int years, 10. double amt, double rate) 11. { 12. setName(name); 13. setYears(years); 14. setAmount(amt); 15. setRate(rate); 16. payment = computePayment(); 17. balance = amt; 18. } 19. 20. void Mortgage::makePayment() 21. Training{ Centers 22. // code for applying payment to principal 23. }

24. 25. double Mortgage::getPayment() {return payment; } 26. 27. double Mortgage::getBalance() {return balance; } 28. 29. Evaluationdouble Mortgage::getInterest() {return interest; } 30. 31. double Mortgage::getPrincipal() {return principal; } 32. 33. double Mortgage::computePayment() 34. { 35. // code forCopy calculating amount of monthly payment 36. }

©2016 UMBC Training Centers 7-7 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Public Base Classes 7-8.cpp 1. Evaluation#include 2. 3. using namespace std; 4. 5. #include "Loan.h" 6. #include "Mortgage.h" 7. Copy 8. int main() 9. { 10. Mortgage m("mike", 30, 100000, 7.5); 11. 12. cout << "MONTH\tPAYMENT\tBALANCE" << endl; 13. 14. for (int i = 1; i <= 12; i++) 15. { 16. m.makePayment(); 17. cout << i << "\t" << m.getPayment() 18. << "\t" << m.getBalance() 19. << "\t" << m.getInterest() 20. << "\t" << m.getPrincipal() << endl; 21. } 22. Training Centers 23. return 0; 24. }

Evaluation Copy

©2016 UMBC Training Centers 7-8 C++ PROGRAMMING CHAPTER 7: INHERITANCE

The protected Access Level • TheEvaluation code for computePayment and makePayment() is dependent on data from the base class.

• If base class data is private, then even derived class functions cannotCopy access them. This is true even though a derived class inherits data from its base class.

• In this example, the data contained within each object is displayed below. Therefore, we have encountered the unusual situation where a derived class object cannot access its base class portions.

Loan Mortgage

name name Trainingamount Centers amount rate rate years years

payment balance Evaluation Base class portion principal of derived class. interest

• You can solve this problem by using the base class public interface. Alternately,Copy you can use the protected access level.

©2016 UMBC Training Centers 7-9 C++ PROGRAMMING CHAPTER 7: INHERITANCE

The protected Access Level • If aEvaluation member is protected, then it is declared as public with respect to derived classes but declared as private with respect to the rest of the program. • This means thatCopy these items can be accessed in deeper derived classes as well.

• If you are implementing a set of classes, some of which will be base classes for derived classes, then it is a good idea that these classes declare their data protected rather than private. This makes it easier for derived class functions to access their base class data. rate rather than getRate() amount rather than getAmount() Training Centers

Evaluation Copy

©2016 UMBC Training Centers 7-10 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Member Initialization Lists

• There is an important issue relating to inheritance in C++ thatEvaluation we have overlooked. Since a derived class contains base class data, any constructor in the derived class is responsible for initializing its base class data.

• In the code below,Copy this is handled through the set member functions provided by the Loan class. Mortgage::Mortgage(string name, int years, double amt, double rate) { setName(name); setYears(years); setAmount(amt); setRate(rate); payment = computePayment(); balance = amt; } Training Centers • Since the compiler is well aware of the inheritance relationship between Loan and Mortgage, it expects that any Mortgage constructor will call a Loan constructor to initializeEvaluation the Loan data inside the Mortgage object. • The initialization is handled by a member initialization list. When we last visited this topic, it was to ensure that contained objects had their constructors called from within containing constructors.Copy Line::Line(const Point & a1, const Point & a2) : p1(a1), p2(a2) {}

©2016 UMBC Training Centers 7-11 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Member Initialization Lists

• In this case, there are no contained objects but rather an inheritanceEvaluation relationship. Therefore, the initialization list simply names the appropriate constructor. Mortgage::Mortgage(string name, int years, double amt, double rate) : Loan(name,Copy years, amt, rate) { payment = computePayment(); balance = amt; }

• If you leave out the initialization list, the compiler will try to execute the default Loan constructor. If one is not present, an error is issued.  InTraining fact, Mortgage.cpp will not compileCenters for that reason.

Evaluation Copy

©2016 UMBC Training Centers 7-12 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Member Initialization Lists

• Working with initialization lists is simple. Regardless of theEvaluation depth of an inheritance hierarchy, a constructor anywhere in the hierarchy need only be responsible for its immediate base class.

• Therefore, if anCopy AdjustableRateMortage is derived from Mortgage, AdjustableRateMortgage constructors need only call the Mortgage constructor, which in turn will call the Loan constructor.

Loan

Mortgage Training Centers

AdjustableRate Mortgage

• FollowingEvaluation is the skeleton code for such a scenario. Copy

©2016 UMBC Training Centers 7-13 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Member Initialization Lists 7-14.cpp 1. Evaluation#include 2. using namespace std; 3. 4. class Loan 5. { 6. public: 7. Loan() Copy 8. { 9. cout << "Loan Constructor" << endl; 10. } 11. int getID() { return 1; } 12. }; 13. 14. class Mortgage : public Loan 15. { 16. public: 17. Mortgage() 18. { 19. cout << "Mortgage Constructor" << endl; 20. } 21. int getID() { return 2; } 22. Training}; Centers 23. 24. class AdjustableRateMortgage : public Mortgage 25. { 26. public: 27. AdjustableRateMortgage() 28. { 29. cout << "ARM Constructor" << endl; 30. Evaluation } 31. int getID() { return 3; } 32. }; 33. 34. int main() 35. { 36. AdjustableRateMortgageCopy arm; 37. return 0; 38. }

©2016 UMBC Training Centers 7-14 C++ PROGRAMMING CHAPTER 7: INHERITANCE

What Isn’t Inherited • NotEvaluation all public and protected function members are inherited under public derivation.

• Constructors are not inherited. This makes sense because constructing a base class object is very different from constructingCopy a derived class object.

• Destructors are also not inherited. A derived class may have its own cleanup to handle and, therefore, cannot rely on a base class destructor.

• Assignment operators are inherited but typically need to be overridden. A base class assignment could never knowTraining about assigning derived classCenters data.

Evaluation Copy

©2016 UMBC Training Centers 7-15 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Assignments Between Base and Derived Objects

• Any derived object can be assigned to a base class object EvaluationMortgage because of the is-a relationship. That is, a is a Loan. However, the opposite is not true. Loan myLoan; Mortgage myMortgage; AdjustableRateMortageCopy myArm;

myLoan = myArm; myLoan = myMortgage;

• After the last assignment, myLoan consists of the sliced Mortgage, the Loan portion of myMortgage.

• Likewise, a base class pointer can be assigned the address of any derived object. The opposite is not true (i.e.,Training it is illegal to assign the addressCenters of a base class object to a derived class pointer). Loan myLoan, *lp; Mortgage myMortgage; AdjustableRateMortage myArm, *armp;

lpEvaluation = &myLoan; lp = &myArm; lp = &myMortgage;

armp = &myLoan; // ERROR Copy • A base class reference can refer to a base class object or an object of any derived class type. Again, the opposite is not true (i.e., a reference of a derived class type cannot refer to a base class object).

©2016 UMBC Training Centers 7-16 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Assignments Between Base and Derived Objects

• A related issue concerns the use of the cast operator with classEvaluation types. Recall that a cast creates a temporary copy of a data value as a different type for the purpose of assignment, initialization, or argument passing. For example: int i; Copy double d = 3.5;

i = (int) d; // cast operator is data // type inside of parentheses

• A base class pointer can be cast to a derived class pointer to allow a call to a function in the derived class that does not exist in the base class. For example: Loan *lp; AdjustableRateMortageTraining myArm; Centers int id; double c;

lp = &myArm;

id = lp -> getID(); c Evaluation= ((AdjustableRateMortgage *) lp) -> getCap();

• Without the cast in the code above, the compiler complains. class Loan Copyhas no member named getCap

©2016 UMBC Training Centers 7-17 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Compile-Time vs. Run-Time Binding

• Things start to get interesting when a pointer is used to invokeEvaluation a function.

• For example, suppose each class below has a getID() function. WhichCopy getID() function would be executed in the code below?

Loan myLoan, *lp; Mortgage myMortgage; AdjustableRateMortage myArm; int id;

lp = &myLoan; id = lp -> getID()

lp = &myArm; id = lp -> getID(); Training Centers lp = &myMortgage; id = lp -> getID();

• Sometimes one function provides the ideal behavior for a specificEvaluation action independent of the specialized class. For these functions, the developer will always want the base class function to act as the reusable default for that action. • In C++, this is exactlyCopy what you get. In other words, unless you have taken measures to the contrary, the same base class getId() function will be executed in the code above.

©2016 UMBC Training Centers 7-18 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Compile-Time vs. Run-Time Binding • FunctionsEvaluation such as getId(), whose behavior is invariant over specialization, should only be coded in the base class and should be reused by all sub classes.

• On the other hand, some functions are such that their behavior variesCopy over specialization.

• For example, a computePayment() function would be implemented slightly differently depending upon what kind of loan we were considering.

• For functions like this, we would execute the “correct” one on a class-specific basis. • YouTraining could get this behavior by Centersnaming the functions differently in each class. However, then you would have to write code like that shown below. if ( object isa Loan ) LoanComputePayment(); else if ( object isa Mortgage ) MortgageComputePayment(); ...Evaluation

• Code like that shown above is both error-prone and a maintenance hazard.Copy Every time a new class is added, or deleted, each piece of code such as the segment above must be changed.

©2016 UMBC Training Centers 7-19 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Compile-Time vs. Run-Time Binding

• A better solution is to let the compiler handle these details. In EvaluationC++, this is accomplished by simply making the base class function a virtual function.

• You can think of pointers (or references) to class objects in an inheritanceCopy hierarchy as having more than one type.  The type given by the compiler (early type, compile type)  The type given during execution (late type, run time type)

• A virtual function uses the run-time type of the pointer (or reference). This is called late binding.

• A non-virtual function uses the compile time type of theTraining pointer (or reference). This Centers is called early binding.

Evaluation Copy

©2016 UMBC Training Centers 7-20 C++ PROGRAMMING CHAPTER 7: INHERITANCE

virtual Functions • ExperimentEvaluation and observe the effect of adding or removing the keyword virtual in the following program.

7-21.cpp

1. #include 2. using namespaceCopy std; 3. 4. class Loan 5. { 6. public: 7. Loan() { cout << "Loan Constructor" << endl; } 8. 9. virtual int getID() { return 1; } 10. }; 11. 12. class Mortgage : public Loan 13. { 14. public: 15. Mortgage() { cout << "Mortgate Constr" << endl; } 16. Training int getID() { return 2;Centers } 17. 18. }; 19. 20. class AdjustableRateMortgage : public Mortgage 21. { 22. public: 23. AdjustableRateMortgage() 24. { 25. Evaluation cout << "ARM Constructor" << endl; 26. } 27. int getID() { return 3; } 28. }; 29. 30. int main() 31. { Copy 32. Loan *ptr = new AdjustableRateMortgage; 33. cout << "ID = " << ( ptr->getID() ) << endl; 34. return 0; 35. }

©2016 UMBC Training Centers 7-21 C++ PROGRAMMING CHAPTER 7: INHERITANCE

virtual Functions • HereEvaluation are a few syntax caveats having to do with virtual functions.

 You do not have to repeat the virtual keyword in derived classes, although by doing so the readability of the program is enhanced. Copy  A family of virtual functions must all have the same signature or the virtual chain is broken. This means they must have the same: • return type; • argument list; and • const or non-const.

• The keyword virtual can only appear in the class definition. When the virtual function is defined in the functions file, it is a syntax error to use the keyword virtualTraining Centers .

Evaluation Copy

©2016 UMBC Training Centers 7-22 C++ PROGRAMMING CHAPTER 7: INHERITANCE

virtual Functions • HereEvaluation is an example to summarize the differences between virtual and non-virtual functions. First, we define a class named Animal. 7-23.cpp 1. #include Copy 2. #include 3. using namespace std; 4. class Animal 5. { 6. private: 7. static int ids; 8. protected: 9. int id; 10. string name; 11. public: 12. Animal(string n); 13. int getID() const; 14. virtual void speak() const; 15. }; 16. Trainingint Animal::ids = 1; Centers

• This class contains one virtual and one non-virtual function. Here are the Animal functions.

Animal::Animal(string n) Evaluation{ name = n; id = ids++; } int Animal::getID() const { return id;Copy } void Animal::speak() const { cout << "What a zoo" << endl; }

©2016 UMBC Training Centers 7-23 C++ PROGRAMMING CHAPTER 7: INHERITANCE

virtual Functions • EachEvaluation class derived from Animal will use the getID function as a default but will override the speak function. Two such classes, Dog and Lion, are shown next. 7-23.cpp (continued) 17. class Dog : Copypublic Animal 18. { 19. public: 20. Dog(string); 21. virtual void speak() const; 22. }; 23. 24. Dog::Dog(string n) : Animal(n) 25. {} 26. 27. void Dog::speak() const 28. { 29. cout << "Name: " << name << " " << "Woof" << endl; 30. } 31. 32. Trainingclass Lion : public Animal Centers 33. { 34. public: 35. Lion(string); 36. virtual void speak() const; 37. }; 38. 39. Lion::Lion(string n) : Animal(n) {} 40. Evaluation 41. void Lion::speak() const 42. { 43. cout << "Name: " << name << " " << "Roar" << endl; 44. } Copy • Finally, we need a class that can collect many animals. We call this class Collection.

©2016 UMBC Training Centers 7-24 C++ PROGRAMMING CHAPTER 7: INHERITANCE

virtual Functions 7-23.cpp (continued) 45. Evaluationclass Collection 46. { 47. int capacity; 48. int howmany; 49. Animal **p; 50. 51. public: Copy 52. Collection(int number = 10); 53. void addAnimal(Animal & pt); 54. Animal * operator[](int pos); 55. int size(); 56. }; 57. 58. Collection::Collection(int number) 59. { 60. capacity = number; 61. p = new Animal *[capacity]; 62. howmany = 0; 63. } 64. 65. void Collection::addAnimal(Animal & pt) 66. Training{ Centers 67. if ( howmany < capacity ) 68. p[howmany++] = &pt; 69. else 70. cout << "reject "<< pt.getID() << endl; 71. } 72. 73. Animal * Collection::operator[](int pos) 74. Evaluation{ 75. if ( pos >= 0 && pos < howmany ) 76. return p[pos]; 77. else 78. { 79. cout << "Bad value: " << pos << endl; 80. returnCopy 0; 81. } 82. } 83. 84. int Collection::size() { return howmany; }

©2016 UMBC Training Centers 7-25 C++ PROGRAMMING CHAPTER 7: INHERITANCE

virtual Functions • TheEvaluation addAnimal function can take any Animal because the parameter is a reference to an Animal. It places the address of the Animal into an array of Animal pointers.

 operator[] returns an Animal pointer. • Copy Here is the main() function. It simply adds animals to the zoo, a Collection object, and then calls the speak function for each animal. 7-23.cpp (continued)

85. int main() 86. { 87. Collection zoo(10); 88. Animal Annie("mal"); 89. Dog zip("zippy"); 90. Dog chip("chippy"); 91. Lion leo("leo"); 92. Training zoo.addAnimal(zip); Centers 93. zoo.addAnimal(chip); 94. zoo.addAnimal(leo); 95. zoo.addAnimal(Annie); 96. 97. for (int i = 0; i < zoo.size(); i++) 98. zoo[i] -> speak(); 99. 100. Evaluation return 0; 101. }

• The most important part of this code is the loop. The correct speak functionCopy is called based on the type of object being pointed to by the pointer returned from the operator[] function. This is different than selecting the function based on the declared type of the pointer, which is Animal * (base class pointer).

©2016 UMBC Training Centers 7-26 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Polymorphism • virtualEvaluation functions, together with pointers or references, provide a powerful C++ feature.

• Functions whose tasks are "similar but different" should be implemented in this way. This concept is called polymorphismCopy. It is the single most powerful idea in object-oriented programming.

• The previous example demonstrated where the power lies. The animal classes represented a typical scenario.

 A group of objects of various subtypes is placed in a collection.  The collection uses base class pointers.  The collection defines a way of selecting each item in it.  TheTraining selection mechanism returns Centers a pointer (or a reference), which is used to invoke the correct function from a family of classes related by inheritance.

Evaluation Copy

©2016 UMBC Training Centers 7-27 C++ PROGRAMMING CHAPTER 7: INHERITANCE

virtual Destructors • RecallEvaluation that a constructor is automatically executed during object creation. void fun1() { Dog zip(“zippy"); } Copy

• The destructor will automatically be called for local objects, such as zip.

• For heap-based objects, delete must be called explicitly. void fun2() { Dog *zip = new Dog(“zippy"); ... Training... Centers delete zip; }

• Which destructor gets called in the following situation? voidEvaluation fun3() { Animal *zip = new Dog(“zippy"); ... delete zip; } Copy • The answer depends upon whether the destructor is virtual or not. If it is, then the Dog destructor is called. Once a destructor is called in a hierarchy, all destructors up the hierarchy will get called as well.

©2016 UMBC Training Centers 7-28 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Pure virtual Functions • In Evaluationthe Animal hierarchy, it is clear that a Dog and a Lion represent concrete entities.

• On the other hand, Animal is really an abstraction. You have probably seenCopy many dogs and a few lions, but have you ever seen an Animal?

• Classes like Animal should be used to specify prototype information for functions that should be implemented in derived classes.

• These functions are not intended to be implemented in the Animal class. Rather they are intended as a mandate to be implemented in derived classes. • Training Centers When they are implemented in derived classes, they must have the same prototype as their model in the Animal class. Evaluation Copy

©2016 UMBC Training Centers 7-29 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Pure virtual Functions • In EvaluationC++, the following notation is used for functions that are not intended to be implemented. #include #include

using namespaceCopy std;

class Animal { private: static int ids;

protected: int id; string name;

public: Animal(string n); Trainingint getID() const; Centers

virtual void speak() const = 0; virtual void eat() const = 0; virtual void move() const = 0; };

intEvaluation Animal::ids = 1;

• Functions such as speak, eat, and move are called pure virtual functions. The special notation informs the compiler that theseCopy functions will not be implemented in this class, but must be implemented in derived classes.

©2016 UMBC Training Centers 7-30 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Abstract Base Classes

• Any class having one or more pure virtual functions is calledEvaluation an abstract base class. This underlies the fact that it is not a real class but an abstraction.

• Since it does not represent a real class, there can be no objects of this type.Copy Animal a; // error

• Its rationalization is to allow derived classes to inherit a set of interfaces.

• However, there can be pointers to Animal. Animal *pt;

• Training Centers The animal pointer can contain the address of any derived object, such as a Dog or a Lion .

• Abstract base classes make no sense by themselves. TheyEvaluation make sense only as a basis for derived classes. • An abstract base class can be viewed as an interface, which hides implementation details.

• An abstract baseCopy class can have:  "real" functions;  data; and  constructors and destructors.

©2016 UMBC Training Centers 7-31 C++ PROGRAMMING CHAPTER 7: INHERITANCE

An Extended Inheritance Example

• We now present a series of classes that descend from an EvaluationWorker abstract class named . First, we show a hierarchy of these classes.

Worker

Copy

Contractor Employee

Accounting Sales

Worker.h

1. class Worker 2. { 3. Trainingprivate: Centers 4. static int ids; 5. int id; 6. string name; 7. 8. public: 9. Worker(string n); 10. int getId(); 11. Evaluation string getName(); 12. 13. virtual double pay() = 0; 14. virtual void vacation() = 0; 15. }; Copy

©2016 UMBC Training Centers 7-32 C++ PROGRAMMING CHAPTER 7: INHERITANCE

An Extended Inheritance Example • NoticeEvaluation the following two classes, Contractor and Employee. Contractor.h

1. #include "Worker.h" 2. 3. class ContractorCopy : public Worker 4. { 5. public: 6. virtual void review() = 0; 7. };

Employee.h

1. #include "Worker.h" 2. 3. class Employee : public Worker { 4. public: 5. virtual double pension() = 0; 6. virtual void bonus() = 0; 7. Training}; Centers

Evaluation Copy

©2016 UMBC Training Centers 7-33 C++ PROGRAMMING CHAPTER 7: INHERITANCE

An Extended Inheritance Example • EmployeeEvaluation and Contractor do not implement any functions from their base class and are abstract classes.

• Classes derived from Employee must now implement the following. Copy virtual double pay() = 0; virtual void vacation() = 0; virtual double pension() = 0; virtual void bonus() = 0;

• Classes derived from Contractor must implement the following. virtual double pay() = 0; virtual void vacation() = 0; virtual void review() = 0; Training Centers

Evaluation Copy

©2016 UMBC Training Centers 7-34 C++ PROGRAMMING CHAPTER 7: INHERITANCE

An Extended Inheritance Example • HereEvaluation is an example class that derives from Contractor . You will be asked to fill in the details in an exercise. // // Accounting.h // #include "Contractor.h"Copy

class Accounting : public Contractor { ... };

• Here is an example class that derives from Employee. You will be asked to fill in the details in an exercise. // // Sales.h // Training Centers #include "Employee.h"

class Sales : public Employee { ... };Evaluation Copy

©2016 UMBC Training Centers 7-35 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Exercises

1. ImplementEvaluation a Point class and then derive Point3D from Point. Make sure the following program can compile and execute. (See the starters directory for the code.) #include "Point.h" #include "Point3D.h"Copy

#include

using namespace std;

int main() { Point p1(0,1); Point3D p2(2,3,4);

cout << p1.getX() << "," << p1.getY() << endl;

Trainingcout << p2.getX() << "," Centers << p2.getY() << "," << p2.getZ() << endl;

p1.print(); cout << endl;

p2.print(); Evaluation cout << endl;

return 0; } Copy

©2016 UMBC Training Centers 7-36 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Exercises

2. CreateEvaluation an abstract Shape class that serves as a design specification for some concrete classes such as Circle and Square. (See the starters/7-2 directory.) class Shape { Copy protected: MyString shapename; public: Shape(MyString s); virtual ~Shape(); virtual double perimeter() = 0; virtual double area() = 0; const char *getname(); };

class Circle : public Shape { protected:Training Centers double radius; public: Circle(double r, MyString s); ~Circle(); virtual double perimeter(); virtual double area(); };Evaluation

class Square : public Shape { protected: double side;Copy public: Square(double side, MyString s); ~Square(); virtual double perimeter(); virtual double area(); };

©2016 UMBC Training Centers 7-37 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Exercises

ExerciseEvaluation 2 (continued) Now create a few Circle objects and a few Square objects and store their addresses in an array of Shape pointers as shown below. const int SIZECopy = 4;

Shape *ptrs[SIZE];

Circle c1(5.0, "mycircle"); Square s1(10.5, "mysquare"); ...

ptrs[0] = &s1; ptrs[1] = &c1; ...

Finally,Training write several loops, one Centers for each function declared in the Shape class. The loop for the area function is shown below. for (int i = 0; i < SIZE; i++) cout << ptrs[i] -> area() << endl; Evaluation Copy

©2016 UMBC Training Centers 7-38 C++ PROGRAMMING CHAPTER 7: INHERITANCE

Exercises 3. Complete the class hierarchy below by creating the concreteEvaluation classes. Add functionality to these concrete classes as you see fit. Make sure that the minimum functionality for these classes satisfies the mandate implied by the three abstract classes below. (See the starters/7-3Copy directory for starter code.) // Abstract classes // class Worker {}; class Employee : public Worker {}; class Contractor : public Worker {};

// // Concrete classes // class Sales : public Employee {}; class Marketing: public Employee {}; class Legal : public Contractor {}; classTraining Accounting : public CentersContractor {}

Evaluation Copy

©2016 UMBC Training Centers 7-39 C++ PROGRAMMING CHAPTER 7: INHERITANCE

EvaluationThis Page Intentionally Left Blank Copy

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 7-40 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Chapter 8: EvaluationI/O in C++ 1) The iostream Library ...... 8-2

2) Predefined Streams...... 8-3

3) Overloading operator<< ...... 8-4

4) Overloading operator>>Copy...... 8-7

5) Manipulators ...... 8-9

6) Stream States...... 8-12

7) Formatted I/O...... 8-15

8) Disk Files...... 8-17

9) Reading and Writing Objects ...... 8-22

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 8-1 C++ PROGRAMMING CHAPTER 8: I/O IN C++

The iostream Library • In Evaluationorder to perform I/O, several classes and member functions have been defined.

• Collectively, these classes are referred to as the iostream library. Copy • C++ programs should include the iostream header file in order to use functions from this library.

• This file contains many of the I/O classes and prototypes for the member functions of those classes.

• This file also defines certain manipulators, which make theTraining use of the stream objects simpler.Centers

Evaluation Copy

©2016 UMBC Training Centers 8-2 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Predefined Streams • C++Evaluation predefines the following stream objects.

C++ C++ C object class equivalent cin istream stdin coutCopy ostream stdout cerr ostream stderr

• Here are a few functions from class istream. istream& get(unsigned char*, int, char='\n'); istream& get(char & c); istream& read(unsigned char*, int); istream& getline(unsigned char*, int, char='\n'); istream& operator>> (unsigned char*); istream& operator>> (int); istream&Training operator>> (char); Centers

• Here are a few functions from class ostream. ostream& put(char); ostream& write(const unsigned char*, int); ostream& operator<< (unsigned char); ostream&Evaluation operator<< (int); ostream& operator<< (double); Copy

©2016 UMBC Training Centers 8-3 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Overloading operator<< • WeEvaluation have already seen many examples of the << functions. Of course we now know that the line: cout << "what a great class!";

is really the following function in disguise. Copy cout.operator<<("what a great class!");

• Furthermore, the following nested use of this operator: int x = 5; cout << x << x * x;

is really the much more awkward:

cout.operator<<(x).operator<<(x * x); Training Centers • This is only possible if operator<< returns cout or a reference to it. Evaluation Copy

©2016 UMBC Training Centers 8-4 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Overloading operator<< • It wouldEvaluation be convenient to treat user-defined types with the ease in which the built-in types are treated.

 In particular, it would be nice to define operator<< for user defined types. Copy • Take a simple class like Fraction and attempt to overload operator<< as a member function. Like other member functions, we would write: Fraction ratio(1,2); ratio.operator<<(cout);

• Here is the code for the above function. ostream & operator<<(ostream & os) { os << n << "/" << d << endl; Trainingreturn os; Centers }

• This works fine but there is a certain anomaly within it. Since it returns a reference to cout, it could be used as follows.Evaluation ratio << cout << 2;

• This is bizarre since normal use of operator<< is as follows. Copy cout << "hello" << 2;

• Because of this quirk, developers implement operator<< as a non-member function and usually as a friend function.

©2016 UMBC Training Centers 8-5 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Overloading operator<< • HereEvaluation is the usual implementation of operator<<. 8-6.cpp

1. #include 2. using namespace std; 3. 4. class FractionCopy 5. { 6. private: 7. int n, d; 8. 9. public: 10. Fraction(int a, int b) : n(a), d(b) {} 11. 12. friend ostream & 13. operator<< (ostream &, const Fraction &); 14. }; 15. 16. ostream & operator<< (ostream & os, 17. const Fraction & cfr) 18. { 19. Training os << cfr.n << "/" << cfr.d;Centers 20. return os; 21. } Evaluation Copy

©2016 UMBC Training Centers 8-6 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Overloading operator>> • TheEvaluation story is much the same for the input operator. The overloading of operator>> for user-defined classes is typically a friend function. • The only issue hereCopy is the format of the input data. Since user-defined types typically hold several data fields, you might have to alert the user as to how to input the data.

• For example, in the Fraction class, we will assume the user inputs two integers with a divide sign between them, with no intervening spaces.

• The code would look like that shown below.

8-7.cppTraining Centers 1. #include 2. #include 3. #include 4. using namespace std; 5. 6. class Fraction 7. { 8. Evaluationprivate: 9. int n, d; 10. 11. public: 12. Fraction(int a, int b) : n(a), d(b) {} 13. 14. friend ostreamCopy & 15. operator<< (ostream & os, const Fraction & f) 16. { 17. os << f.n << "/" << f.d << endl; 18. return os; 19. }

©2016 UMBC Training Centers 8-7 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Overloading operator>> 8-7.cpp (continued) 20. Evaluation friend istream & 21. operator>> (istream & is, Fraction & f) 22. { 23. char line[100]; 24. 25. is >> line; 26. for (iCopy = 0; i < strlen(line); i++) 27. { 28. if (line[i] == '/') 29. break; 30. } 31. line[i] = '\0'; 32. 33. f.n = atoi(line); 34. f.d = atoi(line + i + 1); 35. 36. return is; 37. } 38. }; 39. 40. int main() 41. Training{ Centers 42. Fraction f(2,3); 43. cout << "Enter a fraction (n/d): "; 44. cin >> f; 45. cout << "You entered " << f; 46. 47. return 0; 48. Evaluation} Copy

©2016 UMBC Training Centers 8-8 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Manipulators

• A manipulator modifies the way in which data output to (orEvaluation input from) a stream is handled.

• To use manipulators in your program, you must include the header file iomanip. Here is an example that demonstrates aCopy few manipulators. 8-9.cpp

1. // 8-9.cpp 2. // 3. #include 4. #include 5. using namespace std; 6. int main() 7. { 8. for (int i = 1; i < 20; i += 2) 9. { 10. cout << setw(5) << setfill('0') 11. << i << " " << setw(5) 12. Training << i * i << endl; Centers 13. } 14. return 0; 15. }

• OutputEvaluation 00001 00001 00003 00009 00005 00025 00007 00049 00009 00081 Copy 00011 00121 00013 00169 00015 00225 00017 00289 00019 00361

©2016 UMBC Training Centers 8-9 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Manipulators • TheEvaluation setw manipulator sets the width of the next output item to a specified value.

 The field width applies to the next output item only.  By default, the output will be right adjusted within the field. • Copy The setfill manipulator pads a field with a specified character. Whereas setw only applies to the next output value, the padding character remains set until it is changed later in the program.

• The endl manipulator flushes the output buffer and places a newline character in the output stream.

 The manipulator flush merely flushes the output buffer but doesTraining not place the newline in the Centers output. • There are also manipulators oct, dec, and hex, which specify the base in which an integer value is output.

 This setting lasts until it is changed in the program.  These manipulators can also be used with an input stream to Evaluationinterpret input expressed in octal, decimal, or hex. Copy

©2016 UMBC Training Centers 8-10 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Manipulators • TheEvaluation setw manipulator can also be used to limit the number of characters extracted from an input stream.

8-11.cpp

1. #include 2. #include Copy 3. #include 4. 5. using namespace std; 6. 7. int main() 8. { 9. char line[10]; 10. 11. while(true) 12. { 13. cin >> setw(10) >> line; 14. 15. if (strcmp(line, "quit") == 0) 16. Training break; Centers 17. 18. cout << line << endl; 19. } 20. 21. return 0; 22. }

Evaluation Copy

©2016 UMBC Training Centers 8-11 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Stream States

• Each stream object has an associated state that is affectedEvaluation by operations on the stream.

• As you shall see, the ios class also contains many constants used Copyin various input and output operations. • A stream state can be examined with the rdstate() function.

• rdstate returns an enumeration type defined in ios. ios::goodbit // last operation succeeded ios::eofbit // at end of file ios::failbit // formatting error ios::badbit // other errors

• Training Centers States can also be retrieved with the following functions.  good()  eof()  Evaluationfail()  bad() Copy

©2016 UMBC Training Centers 8-12 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Stream States

• Here are a few examples to demonstrate some functions Evaluationeof with stream states. First, we will demonstrate the function. 8-13.cpp 1. #include Copy 2. #include 3. 4. using namespace std; 5. 6. int main() 7. { 8. char c[10]; 9. 10. while(cin >> c && ( ! cin.eof() )) 11. { 12. cout << c << endl; 13. } 14. 15. cout << "end of program" << endl; 16. Training Centers 17. return 0; 18. }

Evaluation Copy

©2016 UMBC Training Centers 8-13 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Stream States • NowEvaluation we will demonstrate the good function. 8-14.cpp

1. #include 2. #include 3. 4. using namespaceCopy std; 5. 6. int getAnInt(); 7. 8. int main() 9. { 10. int x; 11. 12. x = getAnInt(); 13. cout << "processing " << x << endl; 14. 15. return 0; 16. } 17. 18. int getAnInt() 19. Training{ Centers 20. int value; 21. 22. cout << "enter an int: " << flush; 23. 24. while(1) 25. { 26. cin >> value; 27. Evaluation if(cin.good()) { 28. cin.ignore(INT_MAX, '\n'); 29. break; 30. } 31. cin.clear(); 32. cin.ignore(INT_MAX, '\n'); 33. Copy 34. cout << "again: " << flush; 35. } 36. 37. return value; 38. }

©2016 UMBC Training Centers 8-14 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Formatted I/O • ClassEvaluation ios controls the placement (insertion or extraction) of characters in streams.

• ios member functions can be used to control attributes of input and output.Copy  cout.width(n) – Specifies minimum number of characters to be used for the next numeric or string output  cout.fill(ch) – Pad field with specified character

• A format state for each stream is controlled by the function flags(). A set of options can be invoked with this function. int x = 100; ios_base::fmtflags options = Training ios::hex | ios::showbase; Centers cout.flags(options); cout << x;

• The above code represents an alternative way of using manipulators.Evaluation • The complete list of options is shown next. Copy

©2016 UMBC Training Centers 8-15 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Formatted I/O

class ios { public:Evaluation // formatting flags enum { skipws = 0x0001, // skip wspace on input left = 0x0002, // left-adjust output right =Copy 0x0004, // right-adjust output internal = 0x0008, // padding after sign dec = 0x0010, // decimal conversion oct = 0x0020, // octal conversion hex = 0x0040, // hex conversion showbase = 0x0080, // use base prefix showpoint = 0x0100, // force decimal point uppercase = 0x0200, // upper-case hex output showpos = 0x0400, // add '+' to pos ints scientific = 0x0800, // 123.45E02 notation fixed = 0x1000, // use 123.45 notation unitbuf = 0x2000, // flush after inserts stdio = 0x4000 // flush stdout, stderr };Training // end of enum Centers }; // end of ios

Evaluation Copy

©2016 UMBC Training Centers 8-16 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Disk Files • TheEvaluation header file fstream defines the following classes. Objects of these classes can be used to perform disk I/O.

 ifstream – disk input  ofstream – diskCopy output  fstream – disk input / output

• If you wanted to read from a particular disk file, you would create an object that is “attached" to that file. For example: ifstream input("datafile");

• On the next page is a simple program that counts lines from files named on the command line. Training Centers

Evaluation Copy

©2016 UMBC Training Centers 8-17 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Disk Files 8-18.cpp 1. Evaluation#include 2. #include 3. 4. using namespace std; 5. 6. int main(int argc, char **argv) 7. { Copy 8. int i = 0; 9. 10. while( --argc > 0 ) { 11. int ct = 0; 12. ifstream input(argv[++i]); 13. 14. if ( ! input ) { 15. cerr << "no such file: " 16. << argv[i] << endl; 17. continue; 18. } 19. char ch; 20. while(input.get(ch)) { 21. if(ch == '\n') 22. Training ct++; Centers 23. } 24. input.close(); 25. cout << ct << " lines: " 26. << argv[i] << endl; 27. } 28. return 0; 29. } Evaluation • Sample run of the program 8-18 file1 file2 myfile file3 Copy  Output 10 lines: file1 13 lines: file2 no such file: myfile 15 lines: file3

©2016 UMBC Training Centers 8-18 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Disk Files • AnEvaluation ifstream object is opened automatically for input. • An ofstream object is opened automatically for output. • An fstream objectCopy is opened automatically for both input and output.

• The following enum values can be given as a second argument to the stream constructors. These give additional input / output options. enum open_mode { in = 0x01, // open for reading out = 0x02, // open for writing ate = 0x04, // seek to eof upon open Trainingapp = 0x08, // Centers append mode: all // additions at eof trunc = 0x10, // truncate if exists nocreate = 0x20, // fails if not exist noreplace = 0x40, // fails if exists binary = 0x80 // binary file, not text };Evaluation • Therefore, if you wanted to open a file for both reads and writes in binary mode so that the open fails if the file does not exist, you would write the following. fstream in(argv[1],ios::binary|Copy ios::nocreate); if( ! in ) cerr << “can’t open “ << argv[1] << endl; • The ! operator has been overloaded to test for open failures.

©2016 UMBC Training Centers 8-19 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Disk Files • OtherEvaluation ostream member functions include the following. ostream & seekp(streampos pos); ostream & seekp(streampos pos, seek_dir dir); streampos tellp(); close(); Copy  Note that streampos is typically defined as long int.

• Other istream member functions include the following. istream & seekg(streampos pos); istream & seekg(streamoff off, seek_dir dir); streampos tellg(); close(); int peek(); istream & putback(char c);

• TheTraining seek functions place the fileCenters at position pos. This position can be measured from various origins such as:

enum seek_dir { beg = 0, cur = 1, end = 2 };

• TheEvaluation tell functions return the current file position as a streampos. Copy

©2016 UMBC Training Centers 8-20 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Disk Files 8-21.cpp 1. Evaluation#include 2. #include 3. using namespace std; 4. 5. int main( ) 6. { 7. fstream alpha("letters",Copy ios::in | 8. ios::out | ios::trunc); 9. 10. if( ! alpha ) 11. { 12. cerr << "can’t open letters" << endl; 13. exit(1); 14. } 15. 16. char digit; 17. for (digit = '0';digit <= '9'; digit++) 18. alpha << digit; 19. 20. cout << "AT POS: " << alpha.tellg() << endl; 21. 22. Training alpha.seekg(0); Centers 23. cout << "AT POS: " << alpha.tellg() << endl; 24. 25. for ( int x = 0; x < 10; x++) 26. { 27. alpha.get(digit); 28. cout << digit; 29. } 30. Evaluation cout << endl; 31. 32. cout << "AT POS: " << alpha.tellg() << endl; 33. return 0; 34. }

• Output Copy AT POSITION: 10 AT POSITION: 0 0123456789 AT POSITION: 10

©2016 UMBC Training Centers 8-21 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Reading and Writing Objects • If youEvaluation use the operator<< function to write your objects to the disk, you will run into some problems. This is because this function actually converts your data from binary to character.

• Therefore, if youCopy write out the fraction 1/3 by using the overloaded operator<< function, your data on the disk will be the three characters. 1/3

 On the other hand, if you write out the fraction 19/23, then five characters will write to the disk. 19/23

 Now imagine trying to read such a file. 1/319/23Training Centers

 Is the first value 1/3 and the second value 19/23 or is the first value 1/31 and the second value 9/23? Evaluation Copy

©2016 UMBC Training Centers 8-22 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Reading and Writing Objects

• The answer is to write the information in binary. The preferredEvaluation function is: ostream& write(const unsigned char*, int);

• The following codeCopy will write a fraction to the disk in the exact format that it is stored in memory.

ofstream output("fractions", ios::binary);

Fraction x(1,3); Fraction y(19,23);

output.write((char *) &x, sizeof(Fraction)); output.write((char *) &y, sizeof(Fraction));

• Since the write function writes data in binary, then the numberTraining of bytes written is independent Centers of the data values written.

• Therefore, it is easy to read the fractions back into memory by using the read function. istream&Evaluation read(const unsigned char*, int); Copy

©2016 UMBC Training Centers 8-23 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Reading and Writing Objects • A programEvaluation to illustrate these functions is shown below. 8-24.cpp

1. #include 2. #include 3. #include 4. Copy 5. using namespace std; 6. 7. void writeit(Fraction & fr,fstream& stream) 8. { 9. cout << "writing " << fr << endl; 10. stream.write((char *) &fr, sizeof(Fraction)); 11. } 12. 13. int main() 14. { 15. fstream f("ratios", ios::in | ios::out 16. | ios::trunc); 17. 18. if ( ! f) { 19. Training cerr << "error opening Centers ratios" << endl; 20. exit(0); 21. }

22. 23. Fraction x(2,3); writeit(x,f); 24. Fraction y(3,4); writeit(y,f); 25. Fraction z(5,6); writeit(z,f); 26. 27. Evaluation f.seekg(0); 28. for (int i = 0; i < 3; i++) 29. { 30. cout << "At pos " << f.tellg(); 31. f.read((char *) &x, sizeof(Fraction)); 32. cout << " " << x; 33. } Copy 34. 35. return 0; 36. }

©2016 UMBC Training Centers 8-24 C++ PROGRAMMING CHAPTER 8: I/O IN C++

Exercises

1. WriteEvaluation the functions operator<< and operator>> for the MyString class. 2. Write a program that prompts the user for a filename and a number.  The program shouldCopy read the file and determine which line lengths are longer than that number.  Write each of those lines and its line number to a file named longer. 3. Write a program that displays fractions whose record numbers appear on the command line.

 For example, the following command line would display the first and second fractions in the data file created by the program on page 8-24, and then would display an error message when processingTraining the last command lineCenters argument. program-name 1 2 8

Evaluation Copy

©2016 UMBC Training Centers 8-25 C++ PROGRAMMING CHAPTER 8: I/O IN C++

This Page Intentionally Left Blank Evaluation Copy

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 8-26 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Chapter 9: EvaluationAdvanced Topics 1) Template Functions ...... 9-2

2) Template Classes...... 9-5

3) Multiple Inheritance ...... 9-8 4) User-Defined Conversions...... Copy 9-12 5) Data Structures ...... 9-15

6) An Iterator Class...... 9-19

7) Exceptions...... 9-23

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 9-1 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Template Functions • NoticeEvaluation the function below that computes the mean of an array of type int. double mean(const int *vals, int amt) { double sum = 0.0; for (int iCopy = 0; i < amt; i++) sum += vals[i]); return sum / amt; }

• Now compare this with the following function that computes the mean of an array of type double. double mean(const double *vals, int amt) { double sum = 0.0; for (int i = 0; i < amt; i++) Training sum += vals[i]); Centers return sum / amt; }

• The two functions are exactly alike except for the type of theEvaluation first parameter. It is easy to imagine other mean functions, which are identical except for their type.

• A better approach is to use the C++ template capability that allows you Copyto write one definition for a family of functions, which differs only by the type of parameters.

©2016 UMBC Training Centers 9-2 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Template Functions

• Templates are sometimes referred to as parameterized typesEvaluation or generics. Here is the template version of the two preceding functions. template double mean(const Type *numbers, int amt) { Copy double sum = 0.0; for (int i = 0; i < amt; i++) sum += numbers[i]; return sum / amt; }

• In the template version, the syntax: template

defines a parameter named Type, which will represent the actualTraining type of the parameter whenCenters the function is built.

 It represents the actual type for a particular invocation of mean.

• The compiler generates code for the appropriate function becauseEvaluation of a particular invocation. double x; double array[100]; int numbers[50]; long values[75]; Copy x = mean(array,100); x = mean(numbers,50); x = mean(values,75);

©2016 UMBC Training Centers 9-3 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Template Functions

• When the compiler sees an instantiation of a template function,Evaluation such as those above, it then builds a real function using the template as a blueprint and substituting the real type for the template parameter.

• When it is aboutCopy to build the real function, the compiler must have the template function in its scope. For this reason, templates cannot be compiled separately. Their source must be visible to their invocation.

• Therefore, template functions are typically coded in files that are included in other files that need them.

• Template files are still thought of as libraries, but be aware that they are source code libraries rather than object codeTraining libraries. Centers

• The mean would work properly for any type which has the += defined. Therefore, if you wanted to write: double result; FractionEvaluation ratios[] = { Fraction(3,4),Fraction(8,3), Fraction(5,9) };

result = mean(ratios, 4);

you would haveCopy to be certain that there was a function that could handle:

double a; Fraction b;

©2016 UMBC Training Centers 9-4 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Template Classes • meanEvaluation is just one good idea for a template function. The C++ standard template library has many other template functions including min, max, merge, and sort. • An entire class Copycan be defined as a template. Data structures make good candidates for template classes. Rather than building one class for a stack of integers and another class for a stack of fractions, etc., you can simply build one template stack based on a parameterized type.

• Here is a look at such a template class. Stack.h

1. template 2. class Stack { 3. private: 4. Training int sp; Centers 5. T *stack; 6. 7. public: 8. Stack(int size = 10); 9. void push(T & value); 10. T pop(); 11. bool isEmpty(); 12. Evaluation};

• When an entire class is a template class, then all of its functions are template functions. The implementation for the template stackCopy functions is shown next.

©2016 UMBC Training Centers 9-5 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Template Classes Stack.cpp 1. Evaluationtemplate 2. Stack::Stack(int amt) 3. { 4. stack = new T[amt]; 5. sp = 0; 6. } 7. Copy 8. template 9. void Stack::push(T& v) 10. { 11. stack[sp++] = v; 12. } 13. 14. template 15. T Stack::pop() 16. { 17. return(stack[--sp]); 18. } 19. 20. template 21. bool Stack::isEmpty() 22. Training{ Centers 23. return sp == 0; 24. }

• Since each function is a template function, each function mustEvaluation begin with the template syntax. • The only other syntax that may look strange is the scope resolution syntax. Since these functions are bound to a template class, Copythis concept is expressed as: bool Stack::isEmpty()

rather than:

bool Stack::isEmpty()

©2016 UMBC Training Centers 9-6 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Template Classes • WeEvaluation now show three separate instantiations of the Stack class for data types int, Fraction, and string. 9-7.cpp

1. #include 2. #include "stack.cpp" 3. using namespaceCopy std; 4. 5. int main( ) 6. { 7. Stack ints(100); 8. int i; 9. for ( i = 0; i < 5; i++) 10. { 11. ints.push(i); 12. } 13. while( ! ints.isEmpty()) 14. cout << ints.pop() << endl; 15. cout << endl; 16. 17. Training Stack fractions(100); Centers 18. for ( i = 0; i < 5; i++) 19. { 20. Fraction f(i, i+1); 21. fractions.push(f); 22. } 23. while( ! fractions.isEmpty()) 24. cout << fractions.pop(); 25. cout << endl; 26. Evaluation 27. Stack words(100); 28. string aWord; 29. cout << "Enter Words: ctrl-d to quit "; 30. while ( cin >> aWord) 31. words.push(aWord); 32. Copy 33. while( ! words.isEmpty()) 34. cout << words.pop() << endl; 35. 36. return 0; 37. }

©2016 UMBC Training Centers 9-7 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Multiple Inheritance

• In all of the inheritance examples that we studied earlier, eachEvaluation derived class had one base class. Some object- oriented languages allow a class to have more than one base class. This is called multiple inheritance.

• Multiple inheritanceCopy can be a controversial topic because it creates a number of programming complications. On the other hand, there are situations for which multiple inheritance is well suited.

• There are several places where multiple inheritance is used in the iostream library. Consider the inheritance diagram below.

ios

Training Centers istream ostream

ifstream ofstream

Evaluationfstream

• Notice that fstream has two base classes. It inherits both functionalityCopy for input and output.

©2016 UMBC Training Centers 9-8 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Multiple Inheritance

class ios {}; Evaluation class istream : public ios {}; class ostream : public ios {}; class ifstream :Copy public istream {}; class ofstream : public ostream {}; class fstream : public istream, public ostream {};

• To demonstrate some of the complications that can occur when using multiple inheritance, consider the following classes.

TrainingTransport Centers

Boat Plane

EvaluationSeaPlane

• Skeleton classes for this hierarchy are shown on the next page. Copy

©2016 UMBC Training Centers 9-9 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Multiple Inheritance 9-10.cpp 1. Evaluation#include 2. using namespace std; 3. 4. class Transport 5. { 6. protected: 7. int x; Copy 8. public: 9. Transport() {} 10. void carry() {} 11. }; 12. 13. class Plane : public Transport 14. { 15. public: 16. Plane() {} 17. void fly() {} 18. }; 19. 20. class Boat : public Transport 21. { 22. Trainingpublic: Centers 23. Boat() {} 24. void motor() {} 25. }; 26. 27. class SeaPlane : public Plane, public Boat 28. { 29. public: 30. Evaluation SeaPlane() { x = 0;} 31. }; 32. 33. int main() 34. { 35. SeaPlane sp; 36. sp.carry();Copy 37. return 0; 38. }

©2016 UMBC Training Centers 9-10 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Multiple Inheritance

• As harmless as the classes appear in the previous hierarchy,Evaluation you will get two errors when you compile the code.

• The variable x defined in the Transport class is inherited by bothCopy Plane and Boat. Therefore, it is inherited twice by SeaPlane ; once through Boat and once through Plane.

• Therefore, when x is referenced in the SeaPlane constructor, it is ambiguous.

• The carry function is also ambiguous when referenced through a SeaPlane object. Training Centers

Evaluation Copy

©2016 UMBC Training Centers 9-11 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

User-Defined Conversions

• Because C++ is a hybrid language consisting of primitive typesEvaluation and object types, there are occasions for various kinds of conversions.

• Most of the time, there is no need to convert between objects and primitives.Copy However, there are occasions when you would want this behavior.

• Consider the following two examples. (1) Fraction x(2,3); double d = x;

(2) MyString word("hello"); char line[100]; strcpy(line,word);

• Training Centers In each case, you would want to convert a class type to a primitive type. In order to allow this kind of behavior, you must write a special function whose name is: operator type() { } Evaluation

where type is the type you wish to return from this function. A class can have more than one of these functions. HereCopy is an example from the Fraction class.

©2016 UMBC Training Centers 9-12 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

User-Defined Conversions

• In the following program, there are two instances of using FractionEvaluation a object that would cause an error. This is because the compiler does not know how to convert a Fraction to the receiving type. int main() { Copy Fraction f(3,7); double d = f; // ERROR cout << d << endl;

string data; data = f; // ERROR cout << data << endl; return 0; }

• However,Training if the Fraction class Centers defines how to convert to the receiving type, then the conversions can be made. This is where the operator() functions come into play.

• In the second example above, in order to avoid ambiguity over which operator function to invoke, an explicit cast needsEvaluation to be used. data = (string) f; // OK Copy

©2016 UMBC Training Centers 9-13 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

User-Defined Conversions

9-14.cppEvaluation 1. #include 2. #include 3. #include 4. 5. using namespace std; 6. Copy 7. class Fraction 8. { 9. private: 10. int n, d; 11. 12. public: 13. Fraction(int a = 0, int b = 1) 14. : n(a), d(b) {} 15. operator double() 16. { 17. return (double) n/d; 18. } 19. operator string() 20. { 21. Training ostringstream output; Centers 22. output << n << "/" << d; 23. return output.str();

24. } 25. }; 26. 27. int main() 28. { 29. Evaluation Fraction f(3,7); 30. double d = f; 31. cout << d << endl; 32. 33. string data("hello"); 34. data = (string) f; 35. cout << dataCopy << endl; 36. 37. return 0; 38. }

©2016 UMBC Training Centers 9-14 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Data Structures

• As an introduction to data structures, we present a simple ListEvaluation class.

• A List is a dynamic data structure so that elements can be added or removedCopy with very little disturbance to other elements of the list.

• By contrast, adding or removing an element of an array can cause a lot of movement of array data items. List.h

1. class List 2. { 3. int howmany; # elements in the list 4. mutable int reps; # for demo purposes 5. 6. struct Item { 7. Training int *data; Centers 8. Item *next; 9.

10. Item (int value) : data(value), next(0) { } 11. }; 12. 13. Item *head; 14. Item *tail; 15. Evaluation 16. public: 17. List( ); 18. ~List( ); 19. 20. unsigned int length() const { return howmany; } 21. int getReps()Copy const { return reps; } 22. 23. void insert(int newElement); 24. 25. int operator[ ](int position) const; 26. };

©2016 UMBC Training Centers 9-15 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Data Structures

• If you have seen lists before, the preceding header will makeEvaluation sense. If you have not, you may need to get a good book on data structures.

• The mutable keyword has nothing to do with lists. It allows an item toCopy be altered inside const functions.

• getReps() returns the number of iterations inside the operator[] function.

• The List functions are shown below.

List.cpp

1. #include 2. Training#include Centers 3. 4. using namespace std; 5. 6. #include "List.h" 7. 8. List::List() : head(0), tail(0), howmany(0), reps(0) 9. { 10. cout << "List Constructor" << endl; 11. Evaluation} 12. 13. List::~List() 14. { 15. Item *scan = head; 16. Item *deleted; 17. while( scanCopy != 0 ) 18. { 19. deleted = scan; 20. scan = scan -> next; 21. delete deleted; 22. } 23. }

©2016 UMBC Training Centers 9-16 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Data Structures List.cpp (continued) 24. Evaluationint List::operator[](int pos) const 25. { 26. Item *ptr; 27. for (ptr = head; pos > 0; pos--) 28. { 29. reps++; 30. ptr = Copyptr -> next; 31. } 32. return ptr -> data; 33. } 34. 35. void List::insert(int newElement) 36. { 37. Item *newItem = new Item(newElement); 38. 39. if (newItem == 0) { 40. cerr << "Memory allocation failed in " 41. << "List::insert" << endl; 42. exit(1); 43. } 44. 45. Training if ( head == 0) Centers 46. head = tail = newItem; 47. else 48. { 49. newItem -> next = head; 50. head = newItem; 51. } 52. 53. Evaluation howmany++; 54. } Copy

©2016 UMBC Training Centers 9-17 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Data Structures • HereEvaluation is a program that uses this List class. 9-18

1. #include 2. using namespace std; 3. 4. #include "List.h"Copy 5. 6. int main( ) 7. { 8. List aList; 9. 10. int a = 20, 11. int b = 30; 12. int c = 40; 13. int d = 50; 14. 15. aList.insert(a); 16. aList.insert(b); 17. aList.insert(c); 18. aList.insert(d); 19. Training Centers 20. for (int i = 0; i < aList.length(); i++) 21. cout << aList [i] << endl; 22. 23. return 0; 24. } Evaluation • To the outside world, this class appears to work without any hitches. However, list processing should be efficient and this code has a bottleneck in the operator[] function. Copy • This function is fine if we are using it for selection. It is inefficient if we are using it for iteration.

©2016 UMBC Training Centers 9-18 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

An Iterator Class

• To see the difference, suppose you simply want to retrieve theEvaluation third item. Then you write: cout << aList[3] << endl;

• However, if youCopy want to iterate over all of the items as in the loop in the previous program, then there are too many loop iterations. We added the getReps() function so you could display the number of repetitions within the operator[] function.

9-19.cpp

1. #include 2. using namespace std; 3. 4. #include "List.h" 5. Training Centers 6. int main(int argc, char **argv) 7. { 8. if(argc != 2){ 9. cerr << "usage: 9-19 " << endl; 10. return 1; 11. } 12. 13. int iterations = atoi(argv[1]); 14. Evaluation int i, j; 15. List aList; 16. 17. for (i = 0; i < iterations; i++) 18. aList.insert(i); 19. 20. for (i = Copy0; i < aList.length(); i++) 21. j = aList[i]; 22. 23. cout<< "Reps: " << aList.getReps() << endl; 24. 25. return 0; 26. }

©2016 UMBC Training Centers 9-19 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

An Iterator Class

• Observe the values that the program returns for various commandEvaluation line arguments. 50 iterations -> 1225 repetitions 52 iterations -> 1326 repetitions 100 iterations -> 4950 repetitions

• Copy There needs to be a more economical way of iterating through the loop.

• An iterator is an object, which behaves like a pointer. Therefore, it usually has operations that model pointer operations.

 ++ move the iterator to the next element  -- move the iterator to the previous element  *Training retrieve the element at current Centers position of the iterator

• Usually an iterator is defined on a container class such as a list, vector, or set. To allow convenient access to the container's data, the iterator class is typically declared as a friendEvaluation of the container class. • Iterators are designed for efficient delivery of the next element of a container. We will see that an iterator can solve the problemCopy demonstrated in the previous program. • An iterator for the List class is shown on the next page.

©2016 UMBC Training Centers 9-20 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

An Iterator Class Iterator.h 1. Evaluation#include "List.h" 2. 3. class Iterator 4. { 5. private: 6. List::Item *currentItem; 7. Copy 8. public: 9. Iterator(const List & aList); 10. Iterator operator++(); 11. int operator*(); 12. bool atEnd() { return (currentItem == 0); } 13. };

Iterator.cpp

1. #include "Iterator.h" 2. 3. Iterator::Iterator(const List & aList) 4. : currentItem(aList.head) 5. Training{} Centers 6. 7. int Iterator::operator*() 8. { 9. return currentItem -> data; 10. } 11. 12. Iterator Iterator::operator++() 13. Evaluation{ 14. if (currentItem) 15. currentItem = currentItem -> next; 16. } 17. 18. return *this; 19. } Copy

©2016 UMBC Training Centers 9-21 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

An Iterator Class • TheEvaluation basic ideas are demonstrated below.

9-22.cpp

1. #include 2. 3. using namespaceCopy std; 4. 5. #include "List.h" 6. #include "Iterator.h" 7. 8. int main( ) 9. { 10. List myList; 11. 12. int a = 20, b = 30, c = 40; 13. 14. L.insert(a); 15. L.insert(b); 16. L.insert(c); 17. 18. Training Iterator iter(myList); Centers 19. 20. while (! iter.atEnd) 21. { 22. cout << *iter << endl; 23. ++iter; 24. } 25. 26. Evaluation return 0; 27. } Copy

©2016 UMBC Training Centers 9-22 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Exceptions

• Finding errors in a software project is a full-time occupation.Evaluation  Compilers finds syntax errors.  Programmers finds logic errors.  Programmers findsCopy run-time errors such as: • zero divide; • overflow/underflow; and • range error on arrays or pointers.

• The C++ exception mechanism provides a flexible and organized way to 'trap' run-time errors.

• An exception is an object that your code can create when it detects an abnormal condition at run-time. A developer usesTraining the following keywords when Centers using the exception handling mechanism.

 try – the point at which one or more exception handlers are enabled  Evaluationcatch – a piece of code to handle a particular exception  throw – the point at which an exception object is created Copy

©2016 UMBC Training Centers 9-23 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Exceptions • WithinEvaluation a try block, a program can throw an exception that causes a catch block (an exception handler) to be executed. • The exception mechanismCopy is used with an error caused by the program in contrast to those generated by the operating system, such as an alarm or end-of-file.

• Exception handlers are specified in catch clauses that must immediately follow a try block.

• The example below detects cases where:  a subscript is out of range (RangeException); and  aTraining value is (arbitrarily) too big (SizeException Centers). • The program will have normal control flow until an exception is thrown, and then:

 a constructor is invoked to create an exception object Evaluation(RangeException or SizeException); and  the object is thrown to the appropriate catch clause. Copy

©2016 UMBC Training Centers 9-24 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Exceptions • If anEvaluation exception is not thrown, control flows from the try block to beyond the catch blocks.

 There can be any number of catch blocks.

• If a particular thrownCopy exception is not caught by a catch clause in the active function, then the system will try to find a catch clause by popping the stack of function calls until either:

 a matching catch clause is found; or  the stack is totally unwound and a default error is produced.

• In either case above, destructors are called for all local objects in the stack of function calls. • Training Centers To illustrate the exception handling mechanism, we begin with the definition of a Vector class. Vector.h

1. class Vector { 2. private: 3. Evaluation int size; 4. int maxValue; 5. 6. int *p; 7. 8. public: 9. Vector(intCopy sz = 100, int max = 2000); 10. 11. int getValue(int pos); 12. void setValue(int pos, int value); 13. };

©2016 UMBC Training Centers 9-25 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Exceptions Vector.cpp 1. Evaluation#include "Vector.h" 2. #include "SizeException.h" 3. #include "RangeException.h" 4. 5. Vector::Vector(int sz, int max) 6. { 7. size = sz;Copy 8. maxValue = max; 9. 10. p = new int[size]; 11. } 12. 13. int Vector::getValue(int pos) 14. { 15. if (pos >= size || pos < 0) 16. throw RangeException 17. (pos, "getValue: range error"); 18. 19. return p[pos]; 20. } 21. 22. Trainingvoid Vector::setValue(int pos,Centers int value) 23. { 24. if (pos >= size || pos < 0) 25. throw RangeException 26. (pos, "setValue: range error"); 27. 28. if (value > maxValue) 29. throw SizeException 30. Evaluation (value, "setValue: value is too big"); 31. 32. p[pos] = value; 33. } Copy

©2016 UMBC Training Centers 9-26 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Exceptions RangeException.h 1. Evaluationclass RangeException { 2. private: 3. int pos; 4. char msg[100]; 5. 6. public: 7. RangeException(intCopy p, char *m); 8. 9. int getPos(); 10. const char *getMsg(); 11. };

RangeException.cpp

1. #include 2. 3. #include "RangeException.h" 4. 5. RangeException::RangeException(int p, char *m) 6. Training{ Centers 7. pos = p; 8. strcpy(msg, m); 9. } 10. 11. int RangeException::getPos() 12. { 13. return pos; 14. } 15.Evaluation

16. const char * RangeException::getMsg() 17. { 18. return msg; 19. } Copy

©2016 UMBC Training Centers 9-27 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Exceptions SizeException.h 1. Evaluationclass SizeException 2. { 3. private: 4. int val; 5. char msg[100]; 6. 7. public: Copy 8. SizeException(int v, char *m); 9. 10. int getVal(); 11. const char *getMsg(); 12. };

SizeException.cpp

1. #include 2. 3. #include "SizeException.h" 4. 5. TrainingSizeException::SizeException(int Centers v, char *m) 6. { 7. val = v; 8. strcpy(msg, m); 9. } 10. 11. int SizeException::getVal() 12. { 13. return val; 14.Evaluation}

15. 16. const char * SizeException::getMsg() 17. { 18. return msg; 19. } Copy

©2016 UMBC Training Centers 9-28 C++ PROGRAMMING CHAPTER 9: ADVANCED TOPICS

Exceptions 9-29.cpp 1. Evaluation#include 2. 3. using namespace std; 4. 5. #include "Vector.h" 6. #include "SizeException.h" 7. #include "RangeException.h"Copy 8. 9. int main() 10. { 11. try 12. { 13. Vector x(10, 2000); 14. 15. int i; 16. for (i = 0; i < 10; i++) 17. x.setValue(i, i + 10); 18. 19. x.setValue(8,50); 20. x.setValue(5,90); 21. 22. Training for (i = 0; i < 10; i++)Centers 23. cout << x.getValue(i) << endl; 24. } 25. catch (RangeException re) 26. { 27. cout << "RangeException: "; 28. cout << re.getMsg() << endl; 29. cout << "Bad pos = " << re.getPos() << endl; 30. Evaluation exit(1); 31. } 32. catch (SizeException se) 33. { 34. cout << "SizeException: "; 35. cout << se.getMsg() << endl; 36. cout <

• Conversion from int to bool will be implicit

 A new include format/ Old style still accepted #include

 Explicit keywords for operators andTraining or not Centers not_eq bitand bitor or_eq xor xor_eq compl • The C++ Standard Libraries

I/O Stream Library object-oriented input/output DiagnosticsEvaluation Library asserts and exceptions General Utilities Library template versions of !=, >, <=, >= Strings Library complete set of string operations Standard Template Library (STL) Containers Library (fixed size) Copybit_strings (varying size) Iterators Library tools for the STL template functions performing operators Algorithms Library on STL containers using Iterators complex + machine dependent Numerics Library optimizations on numerics

©2016 UMBC Training Centers 10-2 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

The Standard Template Library

• The STL is a group of container classes and template algorithms.Evaluation Data structures like the ones below do not have to be written by developers. vector list set map Copy • Generic algorithms

 Algorithms work on different containers, including built-in types.

• Algorithms are defined in terms of iterators.  Iterators are designed to traverse different kinds of containers.

• Function objects  GeneralizeTraining ordinary functions Centers • Adaptors

 Change the interface to containers • AllocatorsEvaluation  Storage management Copy

©2016 UMBC Training Centers 10-3 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Design Goals • DevelopEvaluation and organize generic, reusable components • Adaptable and efficient • A set of algorithmsCopy sort copy search merge

• Container access operations  Algorithms are written in terms of container access operations provided by iterators.

• C++ compilers support the above approach by using templates. • Training Centers A programmer selects the container and the algorithm. Iterators are used to "select" the container element when applying the algorithm.

C++ compiler EvaluationALGORITHMS <======> CONTAINERS (template function) Iterators (container) Copy

©2016 UMBC Training Centers 10-4 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Design Goals • EasyEvaluation to extend if necessary • Component interfaces are simple. • Each container Copyclass specifies which categories of iterators it provides.

• For each algorithm, it is stated which category of iterators applies.

• Data structures are independent of algorithms.

• Each algorithm operates on a variety of data structures.

• IteratorsTraining mark the beginning and Centers ending of data structures in a consistent way.

Evaluation Copy

©2016 UMBC Training Centers 10-5 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

STL Components • ContainersEvaluation – objects that store collections of other objects Sequence Containers vector, deque, list Sorted Associative set, multiset, map, Containers multimap stack, queue, Container AdaptorsCopy priority_queue

• Algorithms for_each(), find(), Non-Mutating Sequence count(), equal() copy(), swap(), Mutating Sequence reverse() sort(), merge(), Sorting and Searching binary_search() set_union(), TrainingSet operations set_difference() Centers accumulate(), Numeric inner_product() Others min(), max()

• IteratorsEvaluation – used by algorithms to access the elements inside of containers

 Random Access  Bidirectional Copy  Forward  Input  Output

©2016 UMBC Training Centers 10-6 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

STL Components

• Function objects – used to perform some function on the elementsEvaluation of a container  negate  minus  logical_andCopy  less  others

• Adaptors – template classes that provide interface mappings  stack  queue  priority_queueTraining Centers • Allocators – classes that encapsulate information about the memory model the program is using Evaluation Copy

©2016 UMBC Training Centers 10-7 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Iterators

• Generic algorithms are written in terms of iterator parameters.Evaluation

• Iterators behave like pointers, although they may be implemented inCopy other ways. • In the STL, iterators are built so that the operators ++ and * have their usual meanings, whether the iterators are pointers or not.

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 10-8 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Example: vector 10-9.cpp 1. Evaluation#include 2. #include 3. #include 4. 5. using namespace std; 6. 7. template 8. void print(char * title, TYPE & data) 9. { 10. cout << title << " " ; 11. typename TYPE::iterator it = data.begin(); 12. for (; it != data.end(); it++) 13. cout << *it << " "; 14. cout << endl; 15. } 16. 17. vector vec(char* s) 18. { 19. vector x; 20. 21. while (*s != '\0') 22. Training x.push_back(*s++); Centers 23. 24. return x; 25. } 26. 27. int main( ) 28. { 29. vector v = vec("Advanced C++"); 30. Evaluation 31. reverse(v.begin(), v.end()); 32. print("VECTOR:", v); 33. 34. return 0; 35. } Copy

©2016 UMBC Training Centers 10-9 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Example: list 10-10.cpp 1. Evaluation#include 2. #include 3. #include 4. 5. using namespace std; 6. 7. list mlist(char*Copy s) 8. { 9. list x; 10. 11. while (*s != '\0') 12. x.push_back(*s++); 13. 14. return x; 15. } 16. 17. int main() 18. { 19. list list1 = mlist("instructor"); 20. 21. list::iterator lsi = list1.begin(); 22. Training reverse(list1.begin(), list1.end());Centers 23. 24. while(lsi != list1.end()) 25. cout << *lsi++ << endl; 26. 27. return 0; 28. } Evaluation Copy

©2016 UMBC Training Centers 10-10 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Example: set 10-11.cpp 1. Evaluation#include 2. #include 3. #include 4. 5. using namespace std; 6. 7. template 8. void print(char * title, TYPE & data) 9. { 10. cout << title << " " ; 11. typename TYPE::iterator it = data.begin(); 12. for (; it != data.end(); it++) 13. cout << *it << " "; 14. cout << endl; 15. } 16. 17. list makelist(char* s) 18. { 19. list x; 20. while(*s != '\0') 21. x.push_back(*s++); 22. Training Centers 23. return x; 24. } 25. 26. int main() 27. { 28. list list1 = makelist("C++ Course"); 29. set > s; 30. Evaluation list::iterator i; 31. 32. for (i = list1.begin(); i != list1.end(); ++i) 33. s.insert(*i); 34. list list2; 35. print("BEFORE:", list1); 36. set >::iterator k; 37. for (k = s.begin(); k != s.end(); ++k) 38. list2.push_back(*k); 39. print("AFTER:", list2); 40. 41. return 0; 42. }

©2016 UMBC Training Centers 10-11 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Example: map • A mapEvaluation is used to implement associative arrays. In this data structure, a set of values is indexed by a set of keys.

 An is sometimes called a hash or a map.

10-12.cpp Copy 1. #include 2. #include 3. #include 4. 5. using namespace std; 6. 7. int main() 8. { 9. string name; 10. double val; 11. map > acc; 12. while(1) 13. { 14. Training cout << "enter name ";Centers 15. cin >> name; 16. 17. if (name == "quit") 18. break; 19. 20. cout << "enter amount "; 21. cin >> val; 22. Evaluation acc[name]= acc[name] + val; 23. } 24. 25. map >::iterator i; 26. 27. for(i = acc.begin(); i!= acc.end();i++) 28. { Copy 29. cout << (*i).first << " "; 30. cout << (*i).second << endl; 31. } 32. 33. return 0; 34. }

©2016 UMBC Training Centers 10-12 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Example: find 10-13.cpp 1. Evaluation#include 2. #include 3. #include 4. #include 5. using namespace std; 6. 7. template 8. void print(char * title, TYPE & data) 9. { 10. cout << title << " " ; 11. typename TYPE::iterator it = data.begin(); 12. for (; it != data.end(); it++) 13. cout << *it << " "; 14. cout << endl; 15. } 16. 17. int main() { 18. const int SIZE = 6; 19. int x[SIZE] = {2,4,6,8,10,12 }, val; 20. vector V(&x[0], &x[SIZE]); 21. print("VECTOR:", V); 22. Training int y[SIZE] = {1,3,5,7,9,11 Centers }; 23. list L(&y[0], &y[SIZE]); 24. print("LIST:", L); 25. while(1) 26. { 27. cout << "Enter a value (0 to exit) "; 28. cin >> val; 29. if ( val == 0 ) 30. Evaluation break; 31. vector::iterator where; 32. where = find(V.begin(), V.end(), val); 33. if (where != V.end()) 34. cout << "found " << val << "in vector" << endl; 35. 36. list< Copyint >::iterator place; 37. place =find(L.begin(), L.end(), val); 38. if (place != L.end()) 39. cout << "found "<< val << " in list" << endl; 40. } 41. return 0; 42. }

©2016 UMBC Training Centers 10-13 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Example: merge • mergeEvaluation takes two sorted containers and merges them together in sorted order. 10-14.cpp

1. #include 2. #include 3. #include Copy 4. #include 5. using namespace std; 6. 7. template 8. print(char * title, TYPE & data) 9. { 10. cout << title << " " ; 11. typename TYPE::iterator it = data.begin(); 12. for (; it != data.end(); it++) 13. cout << *it << " "; 14. cout << endl; 15. } 16. 17. Trainingint main() Centers 18. { 19. const int SIZE1 = 3; 20. const int SIZE2 = 3; 21. 22. int x[SIZE1] = {6, 8, 10}; 23. int y[SIZE2] = {5 ,7 ,9}; 24. 25. vector < int > result(SIZE1 + SIZE2); 26. Evaluation vector < int > v(&x[0], &x[SIZE1]); 27. 28. print("VECTOR:", v); 29. list< int > l(&y[0], &y[SIZE2]); 30. print("LIST:" ,l); 31. merge(V.begin(), V.end(), l.begin(), l.end(), 32. result.begin());Copy 33. print("VECTOR:", result); 34. 35. return 0; 36. }

©2016 UMBC Training Centers 10-14 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Example: accumulate • accumulateEvaluation takes a beginning and ending address and performs some accumulation on the elements in that range. • The abstract meaningCopy of accumulate is always the same.

• The type of the iterator and the type of the initial value determine how accumulate works. 10-15.cpp

1. #include 2. #include 3. #include 4. #include 5. using namespace std; 6. 7. Trainingint main() Centers 8. { 9. const int SIZE = 5; 10. int x[SIZE] = {2, 3, 5, 7, 11}; 11. 12. vector v(&x[0], &x[SIZE]); 13. int sum; 14. sum = accumulate(v.begin(), v.end(), 0); 15. Evaluation cout << sum << endl; 16. 17. double y[SIZE] = {2.1, 3.1, 5.2, 7.2, 8.1}; 18. list l(&y[0], &y[SIZE]); 19. double tot; 20. tot = accumulate(l.begin(), l.end(), 0.0); 21. cout << totCopy << endl; 22. cout << accumulate(x, x + SIZE, 0) << endl; 23. 24. list ell(&x[0], &x[SIZE]); 25. tot = accumulate(ell.begin(), ell.end(), 0); 26. return 0; 27. }

©2016 UMBC Training Centers 10-15 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Function Objects • TheEvaluation accumulate algorithm uses + to perform the accumulations.

• In the STL, you can use any operation by "parameterizing" a function. Copy • The accumulate algorithm can have an additional parameter, which specifies the function to perform the accumulations.

template T accumulate(It first, It last, T init, BinOp bop) { while (first != last) init = bop(init, *first++); return init; } Training Centers

Evaluation Copy

©2016 UMBC Training Centers 10-16 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Function Objects 10-17.cpp 1. Evaluation#include 2. #include 3. #include 4. #include 5. using namespace std; 6. 7. int mult(intCopy x, int y) 8. { 9. return x * y; 10. } 11. 12. int main() 13. { 14. int x[5] = {2, 3, 5, 7, 11}; 15. vector v(x, x + 5); 16. 17. int p; 18. p = accumulate(v.begin(), v.end(), 1, mult); 19. cout << p << endl; 20. 21. list l(x, x + 5); 22. Training p = accumulate(l.begin(), Centers l.end(), 2, mult); 23. cout << p << endl; 24. return 0; 25. }

• In the above code, an ordinary function was passed to accumulateEvaluation. Instead, we could pass a function object .

• A function object has the function call operator defined and may also carryCopy along other data.

©2016 UMBC Training Centers 10-17 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Function Objects

• In the class below, we have overloaded the function call Evaluation() operator . 10-18.cpp

1. #include 2. #include 3. #include Copy 4. using namespace std; 5. 6. class mult 7. { 8. public: 9. mult() { cout << "mult constructor" << endl; } 10. 11. int operator()(int a, int b) 12. { 13. return a * b; 14. } 15. }; 16. 17. int main() 18. Training{ Centers

19. int x[5] = {2, 3, 5, 7, 11}; 20. vector v(x, x+5); 21. 22. int p ; 23. p = accumulate(v.begin(), v.end(), 1, mult()); 24. cout << p << endl; 25. 26. Evaluation return 0; 27. }

• The last argumentCopy to accumulate is: mult()

• Since mult is a class, the above reference causes the default constructor to be executed.

©2016 UMBC Training Centers 10-18 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Function Objects

• The previous example demonstrated function objects. However,Evaluation suppose we wanted to multiply doubles or some other type? • mult should beCopy written as a template class! • In the STL, many of these function objects come with the library.

 Arithmetic – plus, times, etc. p = accumulate (v.begin(), v.end(), 1, times());

 Comparison – greater, less, etc.  LogicalTraining – logical_and, logical_or Centers, logical_not

Evaluation Copy

©2016 UMBC Training Centers 10-19 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Adaptors • ContainerEvaluation adaptors are simply wrapper classes. stack queue priority_queue • A priority_queue example 10-20.cpp Copy 1. #include 2. #include 3. #include 4. using namespace std; 5. 6. int main() 7. { 8. int value, ans; 9. priority_queue q; 10. while(1) 11. { 12. cout << "0) quit\n1) insert\n2) erase\n->"; 13. cin >> ans; 14. Training if (ans == 0) Centers 15. break; 16. 17. else if (ans == 1) 18. { 19. cout << "insert" << endl; 20. cout << "enter value "; 21. cin >> value; 22. q.push(value); 23. Evaluation } 24. else if ( ans == 2) 25. { 26. if ( q.empty()) 27. cout << "empty\n"; 28. else 29. { Copy 30. cout << "removing " << q.top() << endl; 31. q.pop(); 32. } 33. } 34. }

©2016 UMBC Training Centers 10-20 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Adaptors 10-20.cpp (continued) 35. Evaluation while(! q.empty()) { 36. cout << q.top() << " " ; 37. q.pop(); 38. } 39. cout << endl; 40. 41. return 0;Copy 42. }

Training Centers

Evaluation Copy

©2016 UMBC Training Centers 10-21 C++ PROGRAMMING CHAPTER 10: INTRODUCTION TO THE STANDARD TEMPLATE LIBRARY

Exercises

1. WriteEvaluation a function to determine if the first n elements of two data structures have the same sum.

 The data structure could be a List or a Vector.  The data structures can be passed to the function in either order. Copy  For example: int main() { const int SIZE = 5;

int x[SIZE] = {1, 2, 3, 4, 5}; int y[SIZE] = {5, 4, 3, 2, 1};

list aList(&x[0], &x[SIZE]); vector aVector(&y[0], &y[SIZE]); Training Centers cout << "List and Vector have "; if (sum_of_n(aVector, aList, 5)) cout << "same sum" << endl; else cout << "different sum" << endl;

Evaluation return 0; }

2. Make the mult class on Page 10-18 into a template class. Test your template class by using it with arrays of type int, doubleCopy, and Fraction.

©2016 UMBC Training Centers 10-22 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Appendix A: EvaluationIntroduction 1) Background ...... A-2

2) Environmental Considerations...... A-5

3) A Sample C Program...... A-6 4) Variables and Data TypesCopy ...... A-8 5) Arrays...... A-11

6) Example of a Program Using an int Array ...... A-13

7) Components of a C Program ...... A-14

8) C Operators ...... A-15

9) Examples of the Operators...... A-16

10) Control Structures ...... A-17 11) Functions...... Training Centers A-19 12) Function Prototypes...... A-22 13) Simple I/O...... A-23 Evaluation Copy

©2016 UMBC Training Centers A-1 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Background

• This course presents a broad overview of the C programmingEvaluation language with an emphasis on those parts of C needed for C++. • C++ derives fromCopy a family of C-like languages. • The original C language was developed in the early 1970’s by Brian Kernighan at AT&T. The language was developed to rewrite the UNIX operating system.

• As C’s popularity began to rise, a variety of C compilers began to appear.

• An effort to standardize C was completed in the late 1980’sTraining resulting in the creation Centersof the ANSI (American National Standards Institute) C language.

• C and ANSI C do not differ widely. Evaluation Copy

©2016 UMBC Training Centers A-2 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Background • LikeEvaluation C, ANSI C offers many robust features.  Terse syntax i++; /* Add 1 to a variable */ x *= 10; /* multiply x by 10 */

 High level constructsCopy • while • for • if • switch

 Low level operations • pointers • bit operations • Training Centers With the rise in popularity of Graphical User Interfaces, the Object-Oriented programming paradigm began to emerge as the choice of software developers.

• In the early 1980’s, while at AT&T, Bjarne Stroustrup developedEvaluation the C++ programming language.

• C++ was intended as the Object-Oriented superset of ANSI C. Copy • ANSI C and C++ differ widely.

©2016 UMBC Training Centers A-3 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Background

• Practically speaking, any C program is also a C++ program,Evaluation although there are slight differences.

• Some C language elements are rarely used in C++ and are not coveredCopy in this course. • For the most part, this course covers those C topics that are necessary for C++ programming.

Training Centers

Evaluation Copy

©2016 UMBC Training Centers A-4 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Environmental Considerations

• Programming languages cannot be learned in a vacuum. ThereEvaluation are system utilities that are also involved in the development cycle.

 Editors – vi, edit, notepad, others  Compilers – Microsoft,Copy UNIX compilers, Macs  Language Tools, Debuggers, Profilers, etc.  Operating Systems – UNIX, Windows, NT, Macs  Source File Name Extensions – usually .c  Editing, Linking, and Executing Training Centers

Evaluation Copy

©2016 UMBC Training Centers A-5 C++ PROGRAMMING APPENDIX A: INTRODUCTION

A Sample C Program

• Your instructor will show you how to compile and execute theEvaluation following C program.

1. #include 2. main () 3. { 4. int base Copy= 2; /* define and init */ 5. int exponent = 5; /* define and init */ 6. int result = 1; /* define and init */ 7. int i; /* just define */ 8. 9. for (i = 0; i < exponent; i++) 10. result *= base; 11. 12. /* 13. printf is a function which displays 14. things on the standard output. Each item 15. to be displayed must have a format 16. specifier such as %d for integers, or %f 17. for decimal numbers 18. */ 19. Training printf(“%d to the %d power Centers is %d\n”, 20. base, exponent, result); 21. 22. return 0; 23. }

Evaluation Copy

©2016 UMBC Training Centers A-6 C++ PROGRAMMING APPENDIX A: INTRODUCTION

A Sample C Program • ThingsEvaluation to notice in the previous program  #include

• Include the file stdio.h, which contains information for many C programs, as part of your program. Copy  The \n character

• This is the “new-line” character that forces any following output to appear on the next line.

 main() { } • Every C program will have one main function, which is the place at which your program begins executing.

/*Training */ Centers  • English language comments must be embedded between /* and */ and can span more than one line.

 The () operator Evaluation• System calls, library functions, or user created functions are invoked with the () operator.

 The definitions for the int variables in the above code could have been codedCopy as: int base=2, exponent = 5, result, i;

©2016 UMBC Training Centers A-7 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Variables and Data Types • A variableEvaluation is a name for a portion of memory. base exponent result i • A variable is of a specific data type and needs to be defined before it can be used. Inside a C function, the list of variables mustCopy come before the list of executable statements. /* INCORRECT */ /* CORRECT */ main() main() { { int x = 0; int x = 0; x = x + 5; int y = 5; int y = 5; x = x + 5; x = x + y; x = x + y; } } • A dataTraining type implies: Centers  a fixed chunk of memory; and

 an interpretation on the bits of that memory.

• Here is a list of some of the fundamental C data types. intEvaluation integer unsigned int positive integer long int big integer short int small integer char single character float Copy dec number (maximum 6 digits) double dec number (maximum 15 digits) more precision

©2016 UMBC Training Centers A-8 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Variables and Data Types

• C also offers more complex types. We will talk more aboutEvaluation these types later. Arrays Structures Pointers • The fundamental data types shown on the previous page are general purposeCopy and are used across all problem- solving domains. • One of the central subject matters of C++ is the construction of new data types. These new types would be built in order to “fill in the gaps” left by the programming language.

• Some programs may require the creation and use of more abstract data types such as: WindowTraining Shape Paragraph Centers Airplane LinkedList Array Animal BankAccount

• In C++, a user created type is called a class. A variable created from such a class is called an object.

• ProgrammingEvaluation with these objects is known as object- oriented programming.

• C++ offers more language support for building user created types thanCopy C offers.

©2016 UMBC Training Centers A-9 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Variables and Data Types

• Variable names can consist of as many characters as you wish.Evaluation  Use letters and the underscore character.  Do not use punctuation.  Upper case is differentCopy than lower case.  Names can be of any length.  Conventionally use lower case.

CORRECT INCORRECT temp 25tmp Val Pay Rec. Payroll_Record this.is.it Training Centers

Evaluation Copy

©2016 UMBC Training Centers A-10 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Arrays • AnEvaluation array is an ordered collection of elements, each of which is of the same type as the others.

• An array can be of any type, i.e., int, char, float, double, or a userCopy created type. • Examples of Arrays  int • Uninitialized int numbers[10];

• Initialized int evens[10]={ 0,2,4,6,8,10,12,14,16,18};

 charTraining Centers • Uninitialized char name[20];

• Initialized char text[20] = “some sample text”; Evaluation • Note that the following are totally different! “a” = a string of length 1 ‘a’ = a singleCopy character

©2016 UMBC Training Centers A-11 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Arrays

numbers evens Evaluation0 ? 0 0 1 ? 1 2 2 ? 2 4 3 ? 3 6 4 ? 4 8 5 ? Copy 5 10 6 ? 6 12 7 ? 7 14 8 ? 8 16 9 ? 9 18

• Note below that character arrays are terminated with the null character, a of all zeroes. 1 1 1 1 1 1 1 1 1 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 textTraining s o m e s a m p l Centerse t e x t \0 ? ? ?

name ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

• To select a particular value from an array, use the [ ] operator,Evaluation commonly called the subscript operator. name[0] = ‘A’; /* upper case A */ name[1] = ‘B’; /* upper case B */ name[2] = ‘\0’; /* a byte of 0’s */ numbers[0] = 25; /* first element */ numbers[9] = Copy37; /* last element */ printf(”%d\n”, evens[5]); • Arrays would typically be processed with a looping structure as a while or a for.

©2016 UMBC Training Centers A-12 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Example of a Program Using an int Array • TheEvaluation important thing to notice in the program presented here is the access on each array element.

1. main() 2. { 3. int x[5] = { 1,2,3,4,5 }; 4. int i, end,Copy temp; 5. printf(“print array elements\n”); 6. for (i = 0; i < 5; i = i + 1) 7. printf(“%d “, x[i]); 8. printf(“\nadd 5 to each element\n”); 9. for (i = 0; i < 5; i++) 10. x[i] = x[i] + 5; 11. printf(“print them again\n”); 12. for (i = 0; i < 5; i++) 13. printf(“%d “, x[i]); 14. printf(“\nnow reverse them\n”); 15. end = 4; 16. for (i = 0; i < end; i++) { 17. temp = x[i]; 18. x[i] = x[end]; 19. Training x[end] = temp; Centers 20. end = end – 1; 21. }

22. printf(“print them again\n”); 23. for (i = 0; i < 5; i++) 24. printf(“%d “, x[i]); 25. } Evaluation • Other things to notice  adding one to a variable i = i + 1 orCopy i++

 the for loop  initialization of arrays

©2016 UMBC Training Centers A-13 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Components of a C Program

• A C program contains one or more non-nested functions, Evaluationmain. exactly one of which has the name

• The source code for these functions is usually spread out among several files, but it is not incorrect to have all code in one file. Copy

• Example

1. #include 2. void process() 3. { 4. printf(“process is a simple function\n”); 5. } 6. 7. void domore() 8. { 9. printf(“domore is another function\n”); 10. Training} Centers 11. 12. main() 13. { 14. printf(“BEGIN\n”); 15. process(); 16. domore(); 17. printf(“END\n”); 18. Evaluation}

• Note that the ()Copy operator is the function call operator.

©2016 UMBC Training Centers A-14 C++ PROGRAMMING APPENDIX A: INTRODUCTION

C Operators

• C supports a large set of operators. Some common operatorsEvaluation are listed below. We will see others as we go through the course.

Table of Operators Copy ARITHMETIC * multiplication right to left / division right to left % remaindering right to left + addition left to right - subtraction left to right

BIT WISE ~ bitwise not left to right << left shift left to right >> right shift left to right & bitwise and left to right ^ bitwise exclusive or left to right Training| bitwise inclusive Centers or left to right

LOGICAL ! logical NOT right to left && logical AND left to right || logical OR left to right

Evaluation RELATIONAL < less than left to right <= less than or equal left to right > greater than left to right >= greater than equal left to right == equal left to right != Copynot equal left to right

©2016 UMBC Training Centers A-15 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Examples of the Operators • ArithmeticEvaluation int a = 5, b = 2, c; c = a + b; /* c = 7 */ c = a * b; /* c = 10 */ c = a / b; Copy /* c = 2 */ • Bitwise

unsigned int x = 055; /* 0000000000101101 */ unsigned int y = 046; /* 0000000000100110 */ unsigned int z; z = ~x; /* 1111111111010010 */ z = x & y; /* 0000000000100100 */ z = x | y; /* 0000000000101111 */ z = y << 2; /* 0000000010011000 */ • Some special operators intTraining a = 5, b = 2, c = 3; Centers c += b; /* c = c + b; */ c *= b; /* c = c * b; */ c /= b; /* c = c / b; */ c -= b; /* c = c – b; */ c <<= 2; /* c = c << 2; */ c++; /* c = c + 1; */ ++c;Evaluation /* c = c + 1; */ b = c++; /* b = c; then c=c + 1; */ b = ++c; /* c = c + 1; then b=c; */ • Others sizeof(int) Copy /* how much storage */ sizeof(b) a = (b > c) ? b : c; /* if b > c, a = b */ /* else a = c */

©2016 UMBC Training Centers A-16 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Control Structures

• High-level languages such as C support programs by offeringEvaluation many decision making and looping constructs. int a, b, max; if ( a >= b) { max = a; printf(“%dCopy >= %d\n”, a, b); }

int a, b, max; if ( a >= b) { max = a; printf(“%d >= %d\n”, a, b); } else { max = b; printf(“%d > %d\n”, b, a); }

intTraining prod = 1, number = 5, Centersi = 1; while( i < number) { prod = prod * i; i = i + 1; } Evaluation Copy

©2016 UMBC Training Centers A-17 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Control Structures

int sum = 0; int i;Evaluation for ( i = 1; i <= 10; i++ ) { sum = sum + i; printf(“ sum is: %d\n”, sum); } Copy char line[100]; gets(line); /* read line */ switch(line[0]) { case ‘A’ : case ‘a’ : do_a(); break; case ‘B’ : case ‘b’ : do_b(); break; caseTraining ‘C’ : Centers case ‘c’ : do_c(); break; default: do_err(); break; } Evaluation • Processing an array with a while vs. a for int a[10]; int a[10]; int i; Copy int i; i = 0; for (i = 0; i < 10; i++) while(i < 10) a[i] = 0; a[i++] = 0;

©2016 UMBC Training Centers A-18 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Functions

• The smallest unit that can be compiled in a C program is a function.Evaluation

• A C program is composed of many non-nested functions, exactly one of whichCopy must have the name main. • Each function must have minimally:  a return type;  a name;  a parameter list (which could be empty); and  a body enclosed in a set of curly braces.

• Each function should also have:  aTraining prototype (a specification of a returnCenters type, name, and parameter list).

Evaluation Copy

©2016 UMBC Training Centers A-19 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Functions • ExampleEvaluation 1. #include 2. int multiply(int a, int b) /* return type: int */ 3. { /* name: multiply */ 4. int c; /* arg list: a,b */ 5. c = a * b; 6. return c;Copy 7. } 8. 9. void print(int param) /* return type: void */ 10. { /* name: print */ 11. printf(“%d\n”, param); /* arg list: param */ 12. } 13. 14. main() /* no return type */ 15. { /* name: main */ 16. int x = 10, y = 20, z; /* arg list: empty */ 17. z = multiply(x,y); 18. print(z); 19. } Training Centers • Where functions are placed in a file is irrelevant.

• The main function is the place at which your program beginsEvaluation to execute. • Functions can beCopy in the same file or in different files.

©2016 UMBC Training Centers A-20 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Functions

• So that the compiler can do type checking, you can place theEvaluation interface of a function ahead of the code where it is invoked. (This is mandatory in C++ but not in C!)

1. #include 2. int multiply(int factor1, int factor2); 3. void print(intCopy number); 4. main() 5. { 6. int x = 10, y = 20, z; 7. z = multiply(x,y); 8. print(z); 9. } 10. int multiply(int a, int b) 11. { 12. int c; 13. c = a * b; 14. return c; 15. } 16. void print(int param) 17. { 18. printf(“%d\n”, param); 19. Training} Centers • Type checking would not be possible in the C program below.

1. #include 2. main() 3. { 4. Evaluation int x = 10, y = 20, z; 5. z = multiply(x,y); 6. print(z); 7. } 8. int multiply(int a, int b) 9. { 10. /* AS BEFORECopy */ 11. } 12. void print(int param) 13. { 14. /* AS BEFORE */ 15. }

©2016 UMBC Training Centers A-21 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Function Prototypes

• A function prototype specifies an interface for a function. It carriesEvaluation all the information about a function except the code. return_type name(argument list); • Each of the followingCopy is a correct prototype for the multiply function. The first one is the preferred one. int multiply(int factor1, int factor2); int multiply(int a, int b); int multiply(int, int); • Function prototypes are not required in C but they are required in C++.

Training Centers

Evaluation Copy

©2016 UMBC Training Centers A-22 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Simple I/O

• Many functions in the C language enable the programmer to Evaluationperform input and output.

• The printf function sends data to the display. It requires the names of the items you wish to display and a format specifierCopy for each item. #include main() { int a = 10, b = 20; double x = 10.5, y = 20.45; char name[10] = “michael”;

printf(“%d %d\n”, a, b); printf(“%f %f\n”, x, y); printf(“%s\n”, name); printf(“%c\n”, name[0]); } Training Centers

• The output from the above program would be: 10 20 10.500000 20.450000 michaelEvaluation m Copy

©2016 UMBC Training Centers A-23 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Simple I/O • SimpleEvaluation input can be performed with the scanf function. The use of this function is similar to the printf function with one big exception. • scanf scans theCopy input device (the keyboard) for sequences of characters separated by combinations of blanks, tabs, or new-lines.  Each sequence is converted according to a format supplied by the scanf function.  scanf stops when it has exhausted the format list.  For reasons which we will explain later, scanf must use the & (address operator) in front of every non-array variable.

• Examples intTraining a, b; Centers double amt; char name[100]; scanf(“%d %d”, &a, &b); /* two ints */ scanf(“%d %lf”, &a,&amt); /* int and double */ scanf(“%s”, name); /* a char array */ Evaluation Copy

©2016 UMBC Training Centers A-24 C++ PROGRAMMING APPENDIX A: INTRODUCTION

Exercises

1. WriteEvaluation a C program which prints your name on the display, with your first and last names each on a separate line. 2. Ask the user to input a few numbers. Print the sum of the integers between and including those two numbers. enter the firstCopy number: 10 enter the second number: 15 The sum of the integers between 10 and 15 is 75

3. Add a test to Exercise 2, which assures that the first number is lower than the second number. enter the first number: 10 enter the second number: 8 ERROR: first number should be lower than second number reenter the second number 15 TheTraining sum of the integers between Centers 10 and 15 is 75

4. Write a function which produces the sum of the squares of the two integer arguments handed to the function. Its prototype would be: int sum_of_squares(int side1, int side2); Evaluation Copy

©2016 UMBC Training Centers A-25 C++ PROGRAMMING APPENDIX A: INTRODUCTION

This Page Intentionally Left Blank

Evaluation

Copy

Training Centers

Evaluation Copy

©2016 UMBC Training Centers A-26 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

Appendix B: EvaluationMore I/O in C 1) The printf Function ...... B-2

2) The scanf Function...... B-4

3) The Preprocessor ...... B-5

4) Conditional Compilation...... B-10Copy

5) Avoiding Multiple Inclusion for the Same File ...... B-12

Training Centers

Evaluation Copy

©2016 UMBC Training Centers B-1 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

The printf Function • TheEvaluation standard C library, available to all C and C++ programs, includes a function named printf. int printf(char *control_string, ... ); • printf requiresCopy a few arguments.  The first of which is a format string, all characters of which are printed except: • escape characters (begin with \ character); and • format specifiers (begin with % character).

 The next argument(s) are the values (variables or expressions) to be printed.

• Some of the more common format specifiers are shown below.Training Centers USE SPECIFIER TO PRINT AS %c character %s string %d decimal value %o octal value Evaluation%x hex value %e %f %g floating point %l (ell)Copy long integer

©2016 UMBC Training Centers B-2 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

The printf Function • EachEvaluation specifier can have the following modifiers. MODIFIER MEANING - left justify # display leading 0x or 0 + display numeric sign Copy0 display leading 0's

• Example

1. #include 2. main() 3. { 4. char book[20] = "Fountainhead"; 5. double price = 8.99; 6. printf("2 %s's cost $%.2f\n", 7. book, 2 * price); 8. } Training Centers

ELEMENT IS PRINTED USING RESULTING IN book %s Fountainhead hm * price %.2f 17.98

• EverythingEvaluation else in the control string is printed literally. • Results from above 2 Fountainhead's cost $17.98 Copy

©2016 UMBC Training Centers B-3 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

The scanf Function • scanfEvaluation is the opposite of printf. Its prototype is similar. int scanf(char *control_string, ... ); • Example 1. #include Copy 2. main() 3. { 4. int hm; 5. char book[20]; 6. double price; 7. 8. printf("enter a number "); 9. scanf("%d\n", &hm); 10. printf("enter a title "); 11. scanf("%s\n", book); 12. printf("enter a price "); 13. scanf("%lf\n", &price); 14. printf("%d %s's cost $%.2f\n", 15. hm, book, hm * price); 16. Training} Centers

Evaluation Copy

©2016 UMBC Training Centers B-4 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

The Preprocessor

• When your C program is compiled, it is first preprocessed. TheEvaluation C++ preprocessor provides various support for your code.

 file inclusion  macro expansionCopy  conditional compilation

• There are many definitions and function prototypes that are required across a wide variety of C and C++ applications.

• C and C++ distributions come with many header files containing these items. Rather than encoding these definitions and prototypes for each program that youTraining write, simply include each headerCenters file that is needed for your particular application.

• For example:  If your program uses any string manipulation functions, then it Evaluationshould include the header file .  If your program uses any math functions, it should include the header file Copy.

©2016 UMBC Training Centers B-5 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

The Preprocessor • ExamplesEvaluation #include #include main() { char prev[100], line[100]; strcpy(prev,"");Copy /* empty string */ while(gets(line) != NULL) { if ( strcmp(line,prev) != 0) { printf("%s\n", line); strcpy(prev, line); } } }

#include #include main() { Trainingchar buffer[100]; Centers double n1, n2, n3; printf("enter a base "); gets(buffer); n1 = atof(buffer); printf("enter an exponent "); gets(buffer); n2 = atof(buffer); Evaluationn3 = pow(n1,n2); printf("%f raised to the %f is %f\n", n1, n2, n3); } • In C, functions returningCopy non ints must specify the function prototype before the invocation of the function. In C++, this is mandatory for all functions.

©2016 UMBC Training Centers B-6 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

The Preprocessor • HeaderEvaluation files are always located in standard directories. On UNIX, many can be found in the directories /usr/include and /usr/include/sys. • On other operatingCopy systems, header files are placed in various directories depending upon the specific compiler that is being used. COMPILER DIRECTORY Microsoft Visual C++ 4.0 c:\msdev\include Borland 3.1 c:\tc\include Borland 4.5 c:\bc4\include Any UNIX compiler /usr/include

• There will be occasions when you will need to create your ownTraining header files. Centers • To include a header file in your applications, use the #include directive of the C++ preprocessor.

 You can use either of the two forms below. The first form automatically finds the included file in the specific compiler Evaluationdependent directory. 1) #include

#include #include Copy OR

2) #include "path name to header file" #include "c:\tc\include\stdio.h" #include "c:\tc\include\iostream.h"

©2016 UMBC Training Centers B-7 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

The Preprocessor • ThereEvaluation are other directives besides the #include that are understood by the preprocessor.

• Macros - Symbolic names for constants #define SIZE Copy5 main() { int x[SIZE] = { 1,2,3,4,5 }; int i, end, temp; printf("print array elements\n"); for (i = 0; i < SIZE; i = i + 1) printf("%d ", x[i]); printf("\nadd 5 to each element\n"); for (i = 0; i < SIZE; i++) x[i] = x[i] + 5; printf("print them again\n"); for (i = 0; i < SIZE; i ++) Training printf("%d ", x[i]); Centers }

• Macros, like that above, are more common in C language than in C++. C++ programmers usually use constant integersEvaluation instead. const int MAX = 100; main() { int array[MAX], i; for (i = 0;Copy i < MAX; i++) array[i] = 0; for (i = 0; i < MAX; i++) printf("%d\n", array[i]); }

©2016 UMBC Training Centers B-8 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

The Preprocessor

• The preprocessor also allows definitions that can take arguments.Evaluation #include #define SQUARE(X) ((X) * (X)) main() { Copy int x = 10; int answer; answer = SQUARE(x); printf("%d\n", answer); printf("%d\n", SQUARE(x + 1)); }

• The above macro is more efficient than a function, which might be built to perform the same task.

• BewareTraining of the subtleties of the Centersuse of macros. int result = SQUARE(x++);

Evaluation Copy

©2016 UMBC Training Centers B-9 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

Conditional Compilation

• The preprocessor also allows for conditional compilation byEvaluation allowing directives such as:  #ifdef  #ifndef • Copy Names can be defined in your program in two ways.  As before with #define #define SIZE 50 #define UNIX

 With -D option on the command line $ CC -DUNIX sourcefile.C $ CC -DSIZE=50 sourcefile.C • YouTraining can write code so that it is Centerscompiled as a function of whether a NAME is defined (or not). This is commonly referred to as conditional compilation . #ifdef UNIX #define WORDSIZE 32 #elif PC #defineEvaluation WORDSIZE 16 #endif • The above example defines WORDSIZE on the basis of whether UNIX orCopy PC is defined. • The official ANSI version of #ifdef is: #if defined(UNIX)

©2016 UMBC Training Centers B-10 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

Conditional Compilation

• Often, you may want to do something because of a name NOTEvaluation having been defined yet. #ifndef DEBUG printf("debugging currently off\n"); #else printstatus();Copy #endif

• This feature is most often used to insulate against multiple inclusion of the same file.

 It is common for C++ source files to include many files, each of which could possibly include the same file.  This could lead to more than one inclusion of the same file and/or multiple #defines for the same NAME.

Training Centers

Evaluation Copy

©2016 UMBC Training Centers B-11 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

Avoiding Multiple Inclusion for the Same File • StudyEvaluation the following files carefully. truth.h bool.h #define YES 1 #define TRUE 1 #define NO 0 #define FALSE 0 #define SIZE 100 #define SIZE 50 Copy truth.c bool.c #include "truth.h" #include "bool.h" main() main() { { /* can use YES /* can use TRUE NO, and SIZE FALSE and SIZE */ */ } }

both.c #include "bool.h" #include "truth.h" main()Training Centers { /* can use YES, NO, TRUE, FALSE but SIZE is defined twice = ERROR */ Evaluation} • The first two .c files above compile fine. However, a compile of both.c complains about the name SIZE being redefined with aCopy different value.

©2016 UMBC Training Centers B-12 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

Avoiding Multiple Inclusions for the Same File

• The above problem is commonly solved with the following technique.Evaluation

• The potentially duplicated parts of header files should have "header guardsCopy" such as the ones shown below. truth.h #define YES 1 #define NO 0 #ifndef SIZE #define SIZE 100 #endif

bool.h #define TRUE 1 #define FALSE 0 #ifndef SIZE #define SIZE 50 #endifTraining Centers

Evaluation Copy

©2016 UMBC Training Centers B-13 C++ PROGRAMMING APPENDIX B: MORE I/O IN C

Exercises

1. WriteEvaluation a program that inputs a string of characters and determines how many times the first character occurs in a string. (Note: the strlen function tells you how many characters are in the string.) You must also include the file which containsCopy the prototype for strlen . #include #include main() { char word[100]; int length;

printf("input a string of characters "); scanf("%s",word); length = strlen(word); }

input a string of characters sississippi (s) appears (5) times in the string(sississippi) Training Centers 2. Write a macro that returns the cube of an expression. Does it work correctly for all of the cases below? Do any of the cases below have the side effect of changing x more than was intended?

main() { Evaluation int x = 3; int z; z = CUBE(x); printf("%d %d\n", z, x); /* should be 27 3 */ z = CUBE(x + 1); printf("%d %d\n",Copy z, x); /* should be 64 3 */ z = CUBE(x++); printf("%d %d\n", z, x); /* should be 27 4 */ }

©2016 UMBC Training Centers B-14 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Appendix C: EvaluationAggregates in C 1) Data Types Revisited ...... C-2

2) Aggregate Types...... C-3

3) Arrays...... C-4 4) Structures...... Copy C-6 5) Structures and Functions ...... C-8

6) Bit Fields ...... C-10

7) Enumeration Types...... C-11

Training Centers

Evaluation Copy

©2016 UMBC Training Centers C-1 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Data Types Revisited • WeEvaluation introduced some fundamental data types in Chapter 1.  int  char  float Copy  double

• You can think of the above types as scalar types in that they each hold one value.

• We also mentioned arrays in Chapter 1.  An array is an example of an aggregate.  It is a name that refers to many values.  ATraining particular value is accessed byCenters using the selection operator. int numbers[10]; int temp; temp = numbers[9]; numbers[9] = numbers[0]; numbers[0] = temp; • C Evaluationsupports other kinds of aggregates. Copy

©2016 UMBC Training Centers C-2 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Aggregate Types • arrayEvaluation – an ordered collection of like types int numbers[10]; • structure – a set of named fields of possibly different types but relatedCopy in an application specific way struct Record { char name[50]; double pay; int grade; }; • bit fields – partitioning an integer into bit-sized parts struct birthdate { int month: 4; int day: 5; int year: 7; }; Training Centers

Evaluation Copy

©2016 UMBC Training Centers C-3 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Arrays • NoteEvaluation the following rules about arrays in C. int numbers[10], values[10], i;

 Subscripts start at zero. for (i = 0; i < 10; i++) numbers[i]Copy = values[i];

 If there is a reference outside the array bounds, it may produce a run time error. for (i = 1; i <= 10; i++) numbers[i] = values[i];

 There are few aggregate operations. Each of the following is incorrect. numbers = values; /* ERROR*/ numbers = 0; /* ERROR*/ Training Centers  You cannot compare one array to another and expect meaningful results.

if (numbers == values) printf("will never be true\n");

• AnyEvaluation of the above can be accomplished by writing your own functions. Copy

©2016 UMBC Training Centers C-4 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Arrays

• The standard C library, accessible from all C++ programs, containsEvaluation a variety of functions that work on character arrays. When you use these functions, be sure to include the file containing their prototypes - . char text1[100], text2[100], text3[100]; Copy  Copy a bunch of characters to a character array. strcpy(text1,"hello there, how are you"); strcpy(text2, text1);

 Take the length of a string. int len; len = strlen(text1); /* len = 24 */

 Compare array of characters. if(strcmp(text1, text2) == 0) Trainingprintf("returns 0 if same\n"); Centers if(strcmp(text1, "hello") == 0) printf("text1 contains \"hello\"\n"); • See the file for the prototypes of common stringEvaluation functions. • Note also that all data in C char arrays must terminate with the '\0' characterCopy (a byte of zeroes).

©2016 UMBC Training Centers C-5 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Structures • C Evaluationuses the struct keyword to create user-defined data types. A user-defined type should contain data that has component parts.

• New data types are necessary to atone for gaps in the of aCopy programming language.

• To create a new data type, do the following.  Create the template for one. This declaration is usually placed in a header file. struct Record { char name[50]; double pay; int grade; }; Training Centers  Create as many of them that you need in an application. struct Record emp1, emp2;

 Reference the individual fields using the "." (dot) operator. emp1.nameEvaluation emp1.pay emp1.grade Copy

©2016 UMBC Training Centers C-6 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Structures • A simpleEvaluation example using structures Record.h

1. struct Record { 2. char name[50]; 3. double pay; 4. int grade;Copy 5. };

1. #include // for printf function 2. #include // for strcpy function 3. #include "Record.h" // for Record definition 4. main() 5. { 6. struct Record e1,e2; 7. strcpy(e1.name,"Mike"); 8. e1.pay = 1000.00; 9. Training e1.grade = 12; Centers 10. strcpy(e2.name,"Susan"); 11. e2.pay = 1100.00; 12. e2.grade = 13; 13. 14. printf("%-20s%10.2f%4d\n", e1.name, 15. e1.pay, e1.grade); 16. printf("%-20s%10.2f%4d\n", e2.name, 17. e2.pay, e2.grade); 18. Evaluation}

Copy

©2016 UMBC Training Centers C-7 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Structures and Functions

• In either case in the preceding example, the output statementsEvaluation are lengthy and error prone. It would be better to isolate the output details into a function and call the function as many times as needed.

1. #include // for printf function 2. #include Copy // for strcpy function 3. #include "Record.h" // for Record definition 4. void print(struct Record param) 5. { 6. printf("%-20s%10.2f%4d\n", param.name, 7. param.pay, param.grade); 8. } 9. main() 10. { 11. struct Record e1,e2; 12. strcpy(e1.name,"Mike"); 13. e1.pay = 1000.00; 14. e1.grade = 12; 15. strcpy(e2.name,"Susan"); 16. Training e2.pay = 1100.00; Centers 17. e2.grade = 13; 18. print(e1); // invoke print: pass e1 19. print(e2); // invoke print: pass e2 20. }

• Note that when the print function is called, the parameterEvaluation (param) is sent a copy of the argument (copy of e1 for the first call and e2 for the second). e1 param Name mike Name mike Pay 1000.00Copy Pay 1000.00 Grade 12 Grade 12

©2016 UMBC Training Centers C-8 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Structures and Functions • YouEvaluation could also isolate the initializations. 1. #include 2. #include 3. #include "Record.h" 4. void print(struct Record param) 5. { 6. printf("%-20s%10.2f%4d\n",param.name,Copy 7. param.pay, param.grade); 8. } 9. struct Record 10. initialize(char n[], double p, int g) 11. { 12. struct Record temp; 13. strcpy(temp.name,n); 14. temp.pay = p; 15. temp.grade = g; 16. return temp; 17. } 18. main() 19. { 20. Training struct Record e1, e2; Centers 21. e1 = initialize("Mike",1000.00,12); 22. e2 = initialize("Susan",1100.00,13); 23. print(e1); 24. print(e2); 25. } • initializeEvaluation is an example of a function that returns a structure. Functions tend to remove the clutter in programs. • Note the parameterCopy named n. Its type is char [], a pointer type, to be discussed in the next chapter.

©2016 UMBC Training Centers C-9 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Bit Fields

• A is a space saving device. If you needed to store a birthday,Evaluation you could code the following. int month, day, year; month = 9; day = 19; year = 44; Copy • The above works fine but it wastes memory. These small integers can be packed into a single word. You simply declare a structure with a little added syntax, which specifies the number of bits per field! struct Birthdate { int mo: 4; int day: 5; int year: 7; }; Training Centers mo day year 4 bits 5 bits bits

• Accessing bit fields is the same as accessing structure members.Evaluation struct Birthdate author; author.mo = 9; author.day = 19; author.year = 44;

Copy author mo day year 9 19 44

©2016 UMBC Training Centers C-10 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Enumeration Types

• The enumeration type is a way of making your programs moreEvaluation readable.

• Suppose you wish to write an application that executes different code asCopy a function of the day of the week. 1. // You can write the code in terms of the 2. // integers from 1 to 7 where: 3. // 1 = Sunday, 2 = Monday, 3 = Tuesday, etc. 4. // 5. int i; 6. for ( i = 1; i <= 7; i++) 7. { 8. if ( i == 7 || i == 1) // weekend 9. printf("not open Weekends\n"); 10. else if ( i >= 2 && i <= 5) 11. printf("open 9AM - 5PM Weekdays\n"); 12. else 13. printf("open 9AM - 9PM on Fridays\n"); 14. Training} Centers

• It is too easy to forget (in a program) whether the days of the week start with 0 or start with 1. Evaluation Copy

©2016 UMBC Training Centers C-11 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Enumeration Types • It isEvaluation more readable to define an enumeration type whose values are the days of the weeks.

 Then the code is written in terms of those days rather than the symbolic constants. 1. #include Copy 2. enum Days 3. { 4. Sun, Mon, Tues, Wed, Thurs, Fri, Sat 5. }; 6. main() 7. { 8. enum Days i; 9. for ( i = Sun; i <= Sat; i++) 10. { 11. if ( i == Sat || i == Sun) 12. printf("not open Weekends\n"); 13. else if ( i >= Mon && i <= Thurs) 14. printf("open 9 - 5 Weekdays\n"); 15. else 16. Training printf("open 9 - 9Centers on Fridays\n"); 17. } 18. } Evaluation Copy

©2016 UMBC Training Centers C-12 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

Exercises

1. WriteEvaluation an Account structure that takes a name, an account number, and an initial balance. struct Account { char name[20]; int account; double balance;Copy };

 Write a function that takes a name, a number, and an initial balance and fills an Account.  Write a function that takes an Account and prints it.  Write a function that takes an Account and adds an amount to the balance.  Essentially, you write the functions that make the following program work. main()Training Centers { struct Account me; me = fill("Michael", 1, 0.0); print(me); me = deposit(me, 50.00); print(me); Evaluation}

Copy

©2016 UMBC Training Centers C-13 C++ PROGRAMMING APPENDIX C: AGGREGATES IN C

This Page Intentionally Left Blank Evaluation Copy

Training Centers

Evaluation Copy

©2016 UMBC Training Centers C-14 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Appendix D: EvaluationPointers in C 1) Fundamental Concepts...... D-2

2) Pointer Operations...... D-3

3) Using Pointers to Alter a Function Argument ...... D-5 4) Using Pointers for ArrayCopy Traversal ...... D-6 5) Pointer Arithmetic ...... D-7

6) Sending an Array to a Function ...... D-10

7) Command Line Arguments...... D-13

8) Pointers vs. Arrays...... D-14

9) Sending an Aggregate to a Function ...... D-15

10) Summary of the Uses of Pointers...... D-18 Training Centers

Evaluation Copy

©2016 UMBC Training Centers D-1 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Fundamental Concepts

• A C Program views memory as a huge array of bytes, eachEvaluation of which has an address.

• A pointer variable is a variable that is used to hold the address of anotherCopy variable. • A pointer is defined using the * notation. int *pi, x = 10; char *p, letter; float f, *pf; double price, *pd; • A C pointer must point to a specific type. The address operator & can be used to assign an address to a pointer variable. pi Training= &x; Centers p = &letter pf = &f; pd = &price; Evaluation Copy

©2016 UMBC Training Centers D-2 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Pointer Operations • OnceEvaluation a pointer has been given an address, the * operator can be used to access the value to which the pointer points. pi = &x; p = &letter pd = &price; Copy

printf("%d\n", x); /* output x directly */ printf("%d\n", *pi); /* indirectly */

x = 30; /* change x directly */ *pi = 30; /* indirectly */ • The * is referred to as the indirection operator.  Once a pointer, such as pi, has been given an address, such as &x, then the following expressions are always identical. xTraining *pi Centers • Of course, a pointer can be modified. int x = 50, *px = &x, y = 100; printf("%d\n", *px); /* prints x */ px = &y; printf("%d\n",Evaluation *px); /* prints y */ Copy

©2016 UMBC Training Centers D-3 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Pointer Operations

• A pointer variable can be assigned to another pointer variableEvaluation if the two pointers are of the same type. int x, *px, *py;

px = &x; /* px points to 'x' */ py = px; Copy /* so does py */ • Two pointers of the same type can be compared. if ( px == py ) {

} Training Centers

Evaluation Copy

©2016 UMBC Training Centers D-4 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Using Pointers to Alter a Function Argument • WithoutEvaluation using pointers 1. #include 2. void change_wrong(int a); 3. main() { 4. int a = 10; 5. printf("Before call: %d\n", a); 6. change_wrong(a);Copy 7. printf("After call : %d\n", a); 8. } 9. void change_wrong(int param) { 10. param = param + 1; 11. printf("Inside function: %d\n", param); 12. }

• Output Before function call: 10 Inside the function: 11 After function call: 10 • Training Centers Using pointers

1. #include 2. void change_right(int * a); 3. main() { 4. int a = 10; 5. printf("Before call: %d\n", a); 6. Evaluation change_right(&a); 7. printf("After call: %d\n", a); 8. } 9. void change_right(int * param) { 10. *param = *param + 1; 11. printf("Inside function: %d\n", *param); 12. } Copy

©2016 UMBC Training Centers D-5 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Using Pointers for Array Traversal • ToEvaluation efficiently traverse arrays 1. #include 2. #define N 5 3. int total(int * param, int number); 4. main() 5. { 6. int data[N],Copy result; 7. int i = 1; 8. int *px; 9. for (px = data; px < data + N; px++) 10. *px = i++; 11. result = total(data, N); 12. printf("%d\n", result); 13. } 14. int total(int * param, int number) 15. { 16. int sum = 0, i; 17. for ( i = 0; i < number; i++) 18. sum += *param++; 19. return sum; 20. Training} Centers

• The code above shows many features regarding pointer traversal of arrays.

• In EvaluationC (and C++) an array name represents the address of the beginning of the array in memory. Therefore, each of the following expressions correctly initializes a pointer to the beginning of the array. int *px = data;Copy int *px = &data[0];

©2016 UMBC Training Centers D-6 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Pointer Arithmetic

• Since array names are addresses, the following is always true.Evaluation array == &array[0] • Furthermore, whenever a pointer and an int occur in an expression, Copypointer arithmetic is performed (i.e., the int is scaled by the sizeof what the pointer points to). The sizeof operator specifies the number of bytes reserved for a variable or a type.

• Taking the address of an array element int data[N], *px; px = &data[0];

px data Training 0 1 2Centers 3 4 1000 ---> 1000

*px == data[0] • Since arrays are addresses, each of the following is correct.Evaluation (a) px = &numbers[0]; (b) px = numbers; (c) px = numbers + 0 Copy • The following are equivalent. &numbers[i] == numbers + i

©2016 UMBC Training Centers D-7 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Pointer Arithmetic • In Evaluationthe loop below, the expression px++ adds one to a pointer.

 This makes sense when a pointer points into an array.  The result is that the pointer points to the next element of the array. Copy int *px; for (px = data; px < data + N; px++) *px = i++;

 Likewise, the expression px < data + N is another example of pointer arithmetic.  Since data is an array, it represents an address.  Therefore, data + N is the address that is N many integers higher than data. • Training Centers Note that the loop test fails when px == data + N.

Evaluation Copy

©2016 UMBC Training Centers D-8 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Pointer Arithmetic • In Evaluationa table lookup, it is easy to test for early loop exit. int data[N], *px; for ( px = data; px < data + N; px++) if(*px == specific_value) break; if( px == dataCopy + N) printf("NOT FOUND\n"); else printf("FOUND\n");

• Stepping through backwards for practice for(px = data + N - 1; px >= data; px--) sum += *px;

 px – points initially to last element  px--Training – moves px to Centersan earlier element  px >= data – tests to see if px still points inside the array when the loop test fails, the following is true px == data - 1 Evaluation Copy

©2016 UMBC Training Centers D-9 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Sending an Array to a Function • RecallEvaluation earlier: int result = total(data, N); /* invoke total */

int total(int * param, int number) { int sum = 0, i; for ( i = Copy0; i < number; i++) sum += *param++; return sum; } • Since an array name is an address, when it is passed to a function, the parameter must be a pointer. The cryptic line: sum += *param++;

fetches *param (what param points to) and then increments param. It could have been written as: Training Centers sum += *param; param++;

It also could have been written as:

sumEvaluation = sum + *param; param++; • Note that the expression: *++param Copy is also allowed but that it first increments the pointer before it fetches what it points to.

©2016 UMBC Training Centers D-10 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Sending an Array to a Function

• Many C++ programs use functions from the .Evaluation A few common functions are: int status, length; char line[100], text[100];

// get a lineCopy from the standard input gets(line);

// copy line to text strcpy(text, line);

// compare two character arrays // return 0 if equal // < 0 if text < line // > 0 if text > line status = strcmp(line,text);

// return the length of the // Trainingcharacter string in line Centers length = strlen(line);

• The prototypes for these functions are in the files string.h and stdio.h. These prototypes are useful in documenting an interface. charEvaluation *gets(char *fill_this_array); char *strcpy(char *target, char *source); int strcmp(char *first, char * second); int strlen(charCopy *string);

©2016 UMBC Training Centers D-11 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Sending an Array to a Function

• It is informative to observe how a few of these functions areEvaluation written.

1. #include 2. #include 3. #define MAX 100 4. main() Copy 5. { 6. char line[MAX]; 7. int length; 8. gets(line); 9. length = strlen(line); 10. printf("length of %s", line); 11. printf(" is %d\n", length); 12. } 13. int strlen(char *s) /* s -> line */ 14. { 15. int ct = 0; 16. while(*s != '\0') { /* end of string */ 17. s++; /* no, add 1 to s */ 18. ct++; /* add 1 to ct */ 19. Training } Centers 20. return(ct); // yes, return ct 21. }

• C type strings, i.e. character arrays, must be terminated withEvaluation the null character ('\0'). All of the functions above depend on this.

• In C++, you might build your own String class to make up for some deficienciesCopy of C strings.

©2016 UMBC Training Centers D-12 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Command Line Arguments

• Arguments can be passed in on the command line into a C Evaluationprogram that is executed from the command line.

• These arguments are passed into the main function through two variables.Copy int main( int argc, char **argv )

 argc represents the number of command line arguments, the first argument is always the name of the executing program.  an array of strings of all the command line arguments. It represents a pointer to an array of pointers to characters.

• The following example prints out the first command line argument. int main( int argc, char ** argv) { Training Centers printf("%s\n", argv[1]); return 0; }

• WhenEvaluation executed on the command line the results are as follows. % a.out MyArgument MyArgument % Copy

©2016 UMBC Training Centers D-13 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Pointers vs. Arrays

• When the C compiler sees a subscript, it is translated into pointerEvaluation notation. (Pointers are easier for the machine whereas array subscripts are easier for programmers!) int numbers[N], i; for ( i = 0; i < N; i++) numbers[i]Copy = 0;

becomes:

for ( i = 0; i < N; i++) *(numbers + i) = 0;

(numbers + i) IS AN ADDRESS! *(numbers + i) IS THE VALUE AT THAT ADDRESS!

• Observe two versions of the strcpy Function. // // Training With Pointers Centers // void strcpy(char *s, char *t) { while(*s++ = *t++) ; } //Evaluation // Without Pointers // void strcpy(char *s, char *t) { int i = 0;Copy while(s[i] = t[i]) i++; }

©2016 UMBC Training Centers D-14 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Sending an Aggregate to a Function • ToEvaluation efficiently pass a struct type to a function, first observe the following.

1. struct Fraction { 2. int n, d; 3. }; 4. struct FractionCopy multiply(struct Fraction x, 5. struct Fraction y) 6. { 7. struct Fraction temp; 8. temp.n = x.n * y.n; 9. temp.d = x.d * y.d; 10. return temp; 11. } 12. #include 13. main() 14. { 15. struct Fraction a,b,c; 16. a.n = 2; a.d = 3; 17. b.n = 4; b.d = 3; 18. c = multiply(a, b); 19. Training printf("result is %d/%d\n", Centers c.n, c.d); 20. }

• The line: c = multiply(a,b); Evaluation  calls the multiply function with arguments; and  a and b and passes both structs by value.

• By default, C passesCopy by value. This means that the arguments a and b are copied respectively to the parameters x and y.

©2016 UMBC Training Centers D-15 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Sending an Aggregate to a Function

• You can make the preceding program more efficient by arrangingEvaluation to pass the addresses of the arguments.

1. struct Fraction { 2. int n; 3. int d; 4. }; Copy 5. struct Fraction multiply(struct Fraction * x, 6. struct Fraction * y) 7. { 8. struct Fraction temp; 9. temp.n = x -> n * y -> n; 10. temp.d = x -> d * y -> d; 11. return temp; 12. } 13. #include 14. main() 15. { 16. struct Fraction a,b,c; 17. a.n = 2; a.d = 3; 18. b.n = 4; b.d = 3; 19. Training c = multiply(&a, &b); Centers 20. printf("result is %d/%d\n", c.n,c.d); 21. }

• The increase in efficiency is not without burden. The callerEvaluation of the multiply function must know to pass two addresses now. Likewise, the writer of the function must now use cumbersome notation to access the data fields of the parameter structures. structure_pointer_variable -> member or Copy (*structure_pointer_variable).member

©2016 UMBC Training Centers D-16 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Sending an Aggregate to a Function • NoteEvaluation how the words struct Fraction occur often in the preceding two programs. C allows the facility whereby a new type name is constructed out of another name.

• Copy Frac Both of the above programs can use the name in place of struct Fraction if they code the following typedef.

• Example

1. struct Fraction { 2. int n; 3. int d; 4. }; 5. typedef struct Fraction Frac; 6. Frac multiply(Frac * x, Frac * y) 7. Training{ Centers 8. Frac temp; 9. temp.n = x -> n * y -> n; 10. temp.d = x -> d * y -> d; 11. return temp; 12. } 13. #include 14. main() 15. Evaluation{ 16. Frac a,b,c; 17. a.n = 2; a.d = 3; 18. b.n = 4; b.d = 3; 19. c = multiply(&a, &b); 20. printf("result is %d/%d\n", c.n,c.d); 21. } Copy

©2016 UMBC Training Centers D-17 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Summary of the Uses of Pointers

• In both C and C++, pointers can be used to do the following.Evaluation  Change the value of an argument in a call to a function int a = 10, b = 20; swap(&a,&b); Copy  Traverse Arrays int *px, data[10]; for(px = data; px < data + N; px++) *px = 0;

 Avoid the overhead of passing a large aggregate to a function Fraction a; print(&a); • Recall also that sending an array to a function is passing theTraining address of the array (by default). Centers void print(int *data, int size) { }

int data[10]; print(data,10); • When an array is used with a subscript, the compiler translatesEvaluation the code to pointer notation. data[i] = *(data + i) • Pointers are also heavily used in the construction of sophisticated dataCopy structures like linked lists, trees, stacks, etc.

©2016 UMBC Training Centers D-18 C++ PROGRAMMING APPENDIX D: POINTERS IN C

Exercises

1. WriteEvaluation a C function that computes the average of a set of integers. The prototype should be: double average1(int *data, int amount);

int numbers[10];Copy double answer;

answer = average1(numbers,10);

2. Rewrite the function in (1) by providing an extra argument.

 The extra argument should be filled by the function. void average2(int *data, int amount, double * avg);

intTraining numbers[10]; Centers double answer;

average2(numbers, 10, &answer);

3. Write a function swap, which exchanges two fractions. TheEvaluation prototype should be: void swap(struct Fraction * left, struct Fraction *right);

struct Fraction a,b; a.n = 1; a.d = 3; b.n = 2; Copy b.d = 3; swap(&a,&b);

©2016 UMBC Training Centers D-19 C++ PROGRAMMING APPENDIX D: POINTERS IN C

This Page Intentionally Left Blank

Evaluation

Copy

Training Centers

Evaluation Copy

©2016 UMBC Training Centers D-20 C++ PROGRAMMING APPENDIX E: BIBLIOGRAPHY

Appendix E: EvaluationBibliography 1) Bibliography...... E-2 Copy

Training Centers

Evaluation Copy

©2016 UMBC Training Centers E-1 C++ PROGRAMMING APPENDIX E: BIBLIOGRAPHY

Bibliography • C++Evaluation Language  Teach Yourself C++ 2nd Edition, Herbert Schildt, McGraw Hill  Thinking in C++, Bruce Eckel, Prentice Hall, 1995, ISBN 0-13- 917709-4  The C++ ProgrammingCopy Language , (3rd Edition), Bjarne Stroustrup, Addison Wesley 1996, ISBN 0-201-53992-6  The Evolution of C++, Bjarne Stroustrup, Addison Wesley 1994, ISBN 0-201-54330-3

• Object Oriented Analysis And Design  Object Oriented Modeling and Design, James Rumbaugh, Prentice Hall 1991, ISBN 0-13-629841-9  Object Oriented Design with Applications, Grady Booch, BenjaminTraining Cummings 1991, ISBN Centers 0-8053-0091-0  Design Patterns, Erich Gamma, Addison Wesley 1995, ISBN 0-201-63361-2

• Once You Know C++  Effective C++, Scott Meyers, Addison Wesley 1992, ISBN 0- Evaluation201-56364-9  More Effective C++, Scott Meyers, Addison Wesley, 1996, ISBN 0-201-63371-X  IBM Smalltalk, David N. Smith, Benjamin Cummings Publishing, 1995,Copy ISBN - 0-8053-0808-X

©2016 UMBC Training Centers E-2