141
Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced program design with C++ Lecture 2: Classes

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Embed Size (px)

Citation preview

Page 1: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1

Concordia University

Department of Computer Science and Software Engineering

COMP345

Advanced program design with C++

Lecture 2: Classes

Page 2: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-2

Learning Objectives

Structures

Classes Inheritance

Encapsulation

Information hiding

Friends

Inline functions

Static members

Page 3: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-3

Structures

aggregate data type: array and struct

Recall: aggregate meaning "grouping" Array: collection of values of same type Structure: collection of values of different types

Treated as a single entity, like arrays

Major difference: Must first declare struct Prior to declaring any variables

Page 4: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-4

Structure Types

Declare struct globally (typically)

No memory is allocated Just a "placeholder" for what our struct

will "look like“, i.e. a type declaration

Definition:struct CDAccountV1 //Name of new "type"{

//list members and their typesdouble balance; double interestRate;int term;

};

Page 5: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-5

Declare Structure Variable

With structure type defined, now declarevariables of this new type:CDAccountV1 account;

Just like declaring simple types Variable account now of type CDAccountV1 It contains "member values"

Each of the struct "parts"

Page 6: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-6

Accessing Structure Members

Dot Operator to access members account.balance account.interestRate account.term

Called "member variables" The "parts" of the structure variable Different structs can have same name

member variables Each struct defines its own scope for naming No conflicts

Page 7: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-7

Structure Example: Display 6.1 A Structure Definition (1 of 3)

Page 8: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-8

Structure Example: Display 6.1 A Structure Definition (2 of 3)

Page 9: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-9

Structure Example: Display 6.1 A Structure Definition (3 of 3)

Page 10: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-10

Structure Pitfall

Semicolon after structure definition ; MUST exist:

struct WeatherData{

double temperature;double windVelocity;

}; // REQUIRED semicolon!

Required since you "can" declare structurevariables in this location

e.g. this declares a variable upon struct declaration:

struct WeatherData{…} myData;

Page 11: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-11

Structure Assignments

Given structure

struct CropYield{

int quantity;

int size;} Declare two structure variables:

CropYield apples, oranges; Simple assignments are legal:

apples = oranges; Simply copies each member variable from apples

into member variables from oranges, equivalent to:

apples.quantity = oranges.quantity;apples.size = oranges.size;

Things are not so simple when pointers are involved

Page 12: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-12

Structures as Function Arguments

Passed like any simple data type Pass-by-value Pass-by-reference

Can also be returned by function Return-type is of a type declared by struct Return statement in function definition

sends structure variable back to caller

Page 13: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-13

Initializing Structures

Can initialize at declaration Example:

struct Date{

int month;int day;int year;

};Date dueDate = {12, 31, 2003};

Declaration provides initial data to all three member variables

Page 14: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-14

Classes

Similar to structures Adds member FUNCTIONS Not just member data

Integral to object-oriented programming Focus on objects

Object: Contains data and operations In C++, variables of class type are objects

Page 15: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-15

Class Definitions

Defined similar to structures Example:

class DayOfYear //name of new class type{ public: //information hiding

void output(); //member functionint month;int day;

};

Notice only member function’s prototype Function declaration Function’s implementation is elsewhere, unless inline

Page 16: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-16

Declaring Objects

Declared same as all variables Predefined types, structure types

Example:DayOfYear today, birthday;

Declares two objects of class type DayOfYear

Objects include: Data members

month, day Operations (member functions, methods)

output()

Page 17: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-17

Class Member Access

Members accessed same as structures

today.monthtoday.day

To access member function:

today.output();

Page 18: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-18

Class Member Functions

Must define or "implement" class memberfunctions

Like other function definitions Can be after main() definition Must specify class name in the function header:

void DayOfYear::output(){…}

:: is scope resolution operator Instructs compiler "what class" member is from Item before :: called type qualifier

Page 19: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-19

Class Member Functions Definition

Notice output() member function’sdefinition (in next example)

Refers to member data of class No qualifiers, as function definition is defined “inside the

class scope”, thus has direct access to anything in this scope

Function used for all objects of the class Will refer to "that object’s" data when invoked Example:

today.output(); Displays "today" object’s data

Page 20: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-20

Complete Class Example: Display 6.3 Class With a Member Function (1 of 4)

Page 21: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-21

Complete Class Example: Display 6.3 Class With a Member Function (2 of 4)

Page 22: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-22

Complete Class Example: Display 6.3 Class With a Member Function (3 of 4)

Page 23: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-23

Complete Class Example: Display 6.3 Class With a Member Function (4 of 4)

Page 24: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-24

Dot and Scope Resolution Operator

Used to specify "of what thing" they aremembers

Dot operator: Specifies member of particular object

Scope resolution operator: Specifies what class the function

definition comes from If scope resolution operator not used, this would be defining

a “free function”.

Page 25: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-25

A Class’s Place

Class is full-fledged type Just like data types int, double, etc.

Can have variables of a class type We simply call them "objects“, or “instances”

Can have parameters of a class type Pass-by-value Pass-by-reference

Can use class type like any other type

Page 26: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-26

Encapsulation

Any data type includes Data (range of data) Operations (that can be performed on data)

Example:int data type has:Data range : +-32,767Operations: +,-,*,/,%,logical,etc.

Same with classes But WE specify data, and the operations to

be allowed on our data, using methods and operators

Page 27: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-27

Encapsulation

Encapsulation Means "bringing together as one“

Declare a class get an object

Object is "encapsulation" of Data values Operations on the data (member functions)

Page 28: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-28

Principles of OOP

Information Hiding Some details of how an entity is internally representing or

acting are hidden to the client class

Abstraction Details of how data is manipulated within

ADT/class not known to client class. Only what is necessary to know is available externally.

Encapsulation Bring together data and operations in a same entity, possibly

hiding some.

Page 29: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-29

Public and Private Members

Data in class almost always designatedprivate in definition Upholds principles of OOP Hide data from user Allow manipulation only via operations

Which are member functions

public items (usually member functions)are "user-accessible"

Page 30: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-30

Public and Private Example

Modify previous example:

class DayOfYear { public: void input(); void output();

private: int month; int day;

};|

Data now private Other objects have no direct access

Page 31: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-31

Public and Private Example 2

Given the previous exampleDeclare object:DayOfYear today;

Object today can ONLY accesspublic members

cin >> today.month;// NOT ALLOWED!cout << today.day; // NOT ALLOWED!

Must instead call public operations:today.input();today.output();

Page 32: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-32

Public and Private Style

Can mix public & private

More typically place public first Allows easy viewing of portions that can be

USED by programmers using the class Private data is "hidden", so irrelevant to users

Outside of class definition, cannot change (or even access) private data

Page 33: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-33

Accessor and Mutator Functions

Object needs to "do something" with its data

accessor member functions Allow object to read data Also called "get member functions" Simple retrieval of member data

mutator member functions Allow object to change data Manipulated based on application

Page 34: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-34

Separate Interface and Implementation

User of class need not see details of howclass is implemented Principle of OOP : information hiding, abstraction

User only needs declaration Called "interface" for the class Put in header files (.h)

Implementation of class (definition) hidden Member function definitions elsewhere User need not see them Put in implementation files (.cpp)

Page 35: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-35

Structures versus Classes

Structures Typically all members public No member functions

Classes Typically all data members private Interface member functions public

Technically, same Perceptionally, very different mechanisms

Page 36: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-36

Thinking Objects

Focus for programming changes Before : algorithms center stage OOP : concept (data and operation) is focus

Algorithms still exist They simply focus on their data Are "made" to "fit" the data Are encapsulated into the data types they manipulate

Designing software solution Define variety of objects and how they interact and use one

another’s data and methods

Page 37: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-37

Summary 1

Structure is collection of data elements of different types

Class is used to combine data and functionsinto single unit: notion of class/object

Member variables and member functions Can be public : accessed outside class Can be private : accessed only in a member

function’s definition

Class and structure types can be parameters to functions, basic type to arrays, etc.

Page 38: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-38

Summary 2

C++ class definition Should separate two key parts

Interface

what user needs to know

Implemented in header file (.h)

Implementation

Details of how the class works

Definitions of methods (member functions)

Implemented in the implementation file (.cpp)

Page 39: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-39

Inheritance

Page 40: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-40

Learning Objectives

Inheritance Basics Derived classes, with constructors protected : qualifier Redefining member functions Non-inherited functions

Programming with Inheritance Assignment operators and copy constructors Destructors in derived classes Multiple inheritance

Page 41: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-41

Introduction to Inheritance

Object-oriented programming Powerful programming technique Generally provides abstraction mechanism called inheritance

General form of class is defined Specialized versions then inherit properties of

general class And add to it/modify it’s functionality for it’s

appropriate use

Page 42: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-42

Inheritance Basics

A class inherits members from another class Base class

"General" class from which others derive

Derived class Automatically has base class’s:

Member variables Member functions By transition, also inherits from all ancestor classes

Can then add additional member functionsand variables, or override inherited functions

Page 43: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-43

Derived Classes

Consider example:Class of Employees

Composed of: Salaried employees Hourly employees

Each is a "subset" of employees “is a”, or “kind of” relationship Another might be those paid fixed wage each

month or week Each potentially has a different way to calculate the pay, and

require different data, thus require different classes

Page 44: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-44

Derived Classes

Don’t "need" type of generic "employee" Since no one’s just an "employee“ There is no generic way to calculate pay

General concept of employee is helpful All have names All have social security numbers Associated functions for these "basics" are

same among all employees

So "general" class can contain all thesegeneral "things" about employees This is the concept of “base class”

Page 45: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-45

Employee Class

Many members of Employee class applyto all types of employees Accessor functions Mutator functions Most data items:

SSN Name Pay

We won’t have "objects“, i.e. “instances”, of this class, however

Page 46: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-46

Employee Class

Consider the printCheck() function: Will always be "redefined" in derived classes to match the

different ways to calculate the pay for different kinds of employees

Makes no sense really for "undifferentiated"employee, as Employee does not store enough information to calculate a pay

So function printCheck() in Employee class outputs:

"printCheck called for generic Employee!! Aborting…"

Page 47: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-47

Deriving from Employee Class

Derived classes from Employee class: Automatically have all member variables Automatically have all member functions

Derived class said to "inherit" membersfrom base class

Can then redefine existing membersand/or add new members

Page 48: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-48

Display 14.3 Interface for the Derived Class HourlyEmployee (1 of 2)

Page 49: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-49

Display 14.3 Interface for the Derived Class HourlyEmployee (2 of 2)

Page 50: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-50

HourlyEmployee Class Interface

Note definition begins same as any other #ifndef directive Includes required libraries and namespaces Also includes employee.h, supposing that it Employee is

defined in another file.

And, the heading:

class HourlyEmployee : public Employee{ …

Specifies "publicly inheriting" from Employeeclass

Page 51: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-51

HourlyEmployee Class Additions

Derived class interface only lists new or"to be redefined" members Since all others inherited are already defined i.e.: "all" employees have ssn, name, etc.

HourlyEmployee adds: Constructors wageRate, hours member variables setRate(), getRate(), setHours(), getHours()

member functions

Page 52: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-52

HourlyEmployee Class Redefinitions

HourlyEmployee redefines: printCheck() member function This "overrides" the printCheck() function

implementation from Employee class

Its definition must be in HourlyEmployeeclass’s implementation As do other member functions declared inHourlyEmployee’s interface

New and "to be redefined"

Page 53: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-53

Inheritance Terminology

Common to simulate family relationships Parent class

Refers to base class

Child class Refers to derived class

Ancestor class Class that’s a parent of a parent …

Descendant class Opposite of ancestor

Page 54: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-54

Constructors in Derived Classes

Base class constructors are NOT inherited in derived classes But they can be invoked within a derived class’

constructor Which is all we need!

Base class constructor must initialize allbase class member variables Those inherited by derived class So derived class constructor simply calls it This way, this part is always initialized in the same manner

Page 55: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-55

Derived Class Constructor Example

Consider syntax for HourlyEmployeeconstructor definition:

HourlyEmployee::HourlyEmployee(string theName,string theNumber, double theWageRate,

double theHours): Employee(theName, theNumber),

wageRate(theWageRate), hours(theHours){

//Deliberately empty}

Portion after : is "initialization section" Includes invocation of Employee constructor

Page 56: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-56

Another HourlyEmployee Constructor

A second constructor’s definition:

HourlyEmployee::HourlyEmployee(): Employee(), wageRate(0), hours(0)

{//Deliberately empty

}

Default version of base class constructoris called (no arguments)

Should always invoke one of the baseclass’s constructors

Page 57: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-57

Constructor: No Base Class Call

Derived class constructor should alwaysinvoke one of the base class’s constructors

If you do not: Default base class constructor automatically called

Equivalent constructor definition:

HourlyEmployee::HourlyEmployee(): wageRate(0), hours(0)

{ }

Page 58: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-58

Pitfall: Base Class Private Data

Derived class "inherits" private membervariables But still cannot directly access them Not even through derived class member

functions!

Private member variables can ONLY beaccessed "by name" in member functions of the class they’re defined in.

Page 59: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-59

Pitfall: Base Class Private Member Functions Same holds for base class

member functions

Cannot be accessed outside interface andimplementation of base class

Not even in derived class member function definitions

Page 60: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-60

Pitfall: Base Class Private Member Functions Impact Larger impact here vs. member variables

Member variables can be accessed indirectlyvia accessor or mutator member functions

Member functions simply not available

This is "reasonable" Private member functions should be simply

"helper" functions Should be used only in class they’re defined

Page 61: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-61

The protected Qualifier

visibility classification of class members As private and public Allows access "by name" in derived class

But nowhere else Still no access "by name" in other (non-derived) classes

In class it’s defined acts like private Considered protected in derived class

To allow future derivations

Many feel this "violates" information hiding

Page 62: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-62

Redefinition of Member Functions

Recall interface of derived class: Contains declarations for new member functions Also contains declarations for inherited

member functions to be changed, i.e. redefined Inherited member functions NOT declared:

Automatically inherited unchanged

Implementation of derived class will: Define new member functions Redefine inherited functions as declared

Page 63: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-63

Redefining vs. Overloading

Very different!

Redefining in derived class: SAME parameter list Essentially "re-writes" the same function

Overloading: Different parameter list (nothing else) Defined "new" function that takes

different parameters Overloaded functions must have

different signatures

Page 64: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-64

A Function’s Signature

Recall definition of a "signature": Function’s name Sequence of types in parameter list

Including order, number, types

Signature does NOT include: Return type const keyword &

Page 65: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-65

Accessing Redefined Base Function

When redefined in derived class, baseclass’s definition not "lost"

Can specify its use:

Employee JaneE;HourlyEmployee SallyH;

// calls Employee’s printCheck() function JaneE.printCheck();

// calls HourlyEmployee printCheck() function SallyH.printCheck();

// calls Employee’s printCheck() function SallyH.Employee::printCheck();

Not typical, but useful sometimes

Page 66: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-66

Functions that are not Inherited

All "normal" functions in base class areinherited in derived class

Exceptions: Constructors (though they are automatically called) Destructors (idem) Copy constructor

But if not defined, generates "default" one Recall need to define one for pointers!

Assignment operator If not defined : default one is generated (same with pointers)

Page 67: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-67

Assignment Operators and Copy Constructors

Recall: overloaded assignment operators and copy constructors NOT inherited But can be used in derived class definitions

Typically MUST be used across an inheritance hierarchy!

Similar to how derived class constructorinvokes base class constructor

Absolutely necessary for classes with pointer data members

Page 68: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-68

Assignment Operator Example

Given "Derived" is derived from "Base":

Derived& Derived::operator =(const Derived & rightSide){

//Copying the members of the Base classBase::operator =(rightSide);//coping the members of Derived

}

Notice code line Calls assignment operator from base class

This takes care of all inherited member variables Would then set new variables from derived

class

Page 69: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-69

Copy Constructor Example

Consider:

Derived::Derived(const Derived& Object): Base(Object), …

{…}

After : is invocation of base copy constructor Sets inherited member variables of derived

class object being created Note Object is of type Derived; but it’s also of

type Base, so argument is valid

Page 70: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-70

Destructors in Derived Classes

If base class destructor functions correctly Easy to write derived class destructor

When derived class destructor is invoked: Automatically calls base class destructor! So no need for explicit call

So derived class destructors need only beconcerned with derived class variables And any data they "point" to Base class destructor handles inherited data

automatically

Page 71: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-71

Destructor Calling Order

Consider:class B derives from class Aclass C derives from class B

A B C

When object of class C goes out of scope: Class C destructor called 1st

Then class B destructor called Finally class A destructor is called

Opposite of how constructors are called

Page 72: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-72

"Is a" vs. "Has a" Relationships

Inheritance Considered an "Is a" class relationship e.g., An HourlyEmployee "is a" Employee A Convertible "is a" Automobile

A class contains objects of another classas it’s member data Considered a "Has a" class relationship e.g., One class "has a" object of another

class as it’s data

Page 73: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-73

Protected and Private Inheritance

New inheritance "forms“, vs public inheritance Protected inheritance:

class SalariedEmployee : protected Employee{…}

public members in base class become protected in derived class

Private inheritance:

class SalariedEmployee : private Employee{…}

All members in base class become private in derived class

Page 74: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Friends

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-74

In principle, private and protected members of a class cannot be accessed from outside the class in which they are declared

A friend (function or class) of a class may access the members designated as private or protected.

Friends are functions or classes declared as such within a class

Widely criticized for being a "rogue feature" Makes the language more complex Contradicts the information hiding principle

Page 75: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Friends example (free function)

// friend free function

#include <iostream>

using namespace std;

class CRectangle {

private:

int width, height;

public:

void set_values (int, int);

int area () {return (width * height);}

friend CRectangle duplicate (CRectangle);

};

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-75

Page 76: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Friends example (free function)

void CRectangle::set_values (int a, int b) {

width = a; height = b; }

CRectangle duplicate (CRectangle rectparam) {

CRectangle rectres;

rectres.width = rectparam.width*2;

rectres.height = rectparam.height*2;

return (rectres); }

int main () {

CRectangle rect, rectb;

rect.set_values (2,3);

rectb = duplicate (rect);

cout << rectb.area();

return 0; }

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-76

Page 77: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Friends example (class)#include <iostream>

using namespace std;

class CSquare; //Forward declaration

class CRectangle {

private:

int width, height;

public:

int area () {return (width * height);}

void convert (CSquare a); };

class CSquare {

private:

int side;

public:

void set_side (int a) {side=a;}

friend class CRectangle; };

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-77

Page 78: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Friends example (class)

void CRectangle::convert (CSquare a) {

width = a.side;

height = a.side; }

int main () {

CSquare sqr;

CRectangle rect;

sqr.set_side(4);

rect.convert(sqr);

cout << rect.area();

return 0; }

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-78

Page 79: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Friends example (member function)#include <iostream>

using namespace std;

class B; // Forward declaration

class A {

private:

int a;

public:

A() { a=0; }

void show(A& x, B& y); };

class B {

private:

int b;

public: B() { b=6; }

friend void A::show(A& x, B& y); };

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-79

Page 80: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Friends example (member function)

void A::show(A& x, B& y) {

cout << "A::a=" << x.a << endl;

cout << "B::b=" << y.b << endl; }

int main() {

A a;

B b;

a.show(a,b);

return 0; }

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-80

Page 81: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-81

Multiple Inheritance

Derived class can have more than onebase class! Syntax just includes all base classes

separated by commas:

class derivedMulti : public base1, base2{…}

Possibilities for ambiguity are endless! Dangerous undertaking!

Some believe should never be used Similar/different vs. Java’s interfaces

Page 82: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Multiple inheritance (2 examples)

class Animal {...};

class Mammal : public Animal {...};

class WingedAnimal : public Animal {...};

class Bat : public Mammal, WingedAnimal {...};

class Worker : public Person {…};

class Musician : public Person, Worker {…};

class StudentMusician : public Person, Musician, Worker {…};

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-82

Page 83: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Multiple inheritance

Ambiguities arise when conflicting members are inherited from different classes.

Diamond problem: two inherited classes inherit from a common class. Solved using virtual inheritance

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-83

Page 84: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Virtual Members

Some member function of a class are meant to be redefined in its derived classes : virtual member function, or virtual function.

precede its declaration with the keyword virtual

Upon a polymorphic call, the most specific version is called.

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-84

Page 85: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Virtual members (example)#include <iostream>

using namespace std;

class CPolygon {

protected:

int width, height;

public:

void set_values (int a, int b) { width=a; height=b; }

virtual int area () { return (0); } };

class CRectangle: public CPolygon {

public:

int area () { return (width * height); } };

class CTriangle: public CPolygon {

public:

int area () { return (width * height / 2); } };

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-85

Page 86: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Virtual members (example)

int main () {

CRectangle rect;

CTriangle trgl;

CPolygon poly;

CPolygon * ppoly1 = &rect;

CPolygon * ppoly2 = &trgl;

CPolygon * ppoly3 = &poly;

ppoly1->set_values (4,5);

ppoly2->set_values (4,5);

ppoly3->set_values (4,5);

cout << ppoly1->area() << endl; //20

cout << ppoly2->area() << endl; //10

cout << ppoly3->area() << endl; //0

return 0; }

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-86

Page 87: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Pure virtual functions

A member function can also be made pure virtual by appending it with = 0 after the closing bracket and before the semicolon.

Objects can not be created of a class with a pure virtual function and are called abstract classes. Such abstract data types can only be derived from.

Any derived class inherits the virtual function as pure and must override it (and all other pure virtual functions) with a non-pure virtual function for objects to be created from the derived class, or else it is also itself an abstract class.

An attempt to create an object from a class with a pure virtual function or inherited pure virtual function will be flagged as a compile-time error.

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-87

Page 88: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Pure virtual functions (example)

#include <iostream>

#include <string>

#include <vector>

using namespace std;

class Animal {

public:

Animal(const string & name) : name(name) { }

virtual const string talk() = 0;

const string name; };

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-88

Page 89: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Pure virtual functions (example)

class Cat : public Animal {

public:

Cat(const string & name) : Animal(name) { }

virtual ~Cat() { }

virtual const string talk() { return "Meow!"; } };

class Dog : public Animal {

public:

Dog(const string & name) : Animal(name) { }

virtual ~Dog() { }

virtual const string talk() { return "Arf! Arf!"; } };

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-89

Page 90: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Pure virtual functions (example)

int main() {

Animal * animals [] = { new Cat("Missy"),

new Cat("Mr.Bojangles"),

new Dog("Lassie") };

for(int i = 0; i < 3; i++)

cout << animals[i]->name << ": "

<< animals[i]->talk() << endl;

for(int i = 0; i < 3; i++)

delete animals[i];

return 0; }

// prints the following:

// Missy: Meow!

// Mr. Bojangles: Meow!

// Lassie: Arf! Arf!

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-90

Page 91: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Virtual Inheritance

Base classes may be declared as virtual: virtual inheritance.

Virtual inheritance ensures that only one instance of a base class exists in the inheritance graph

Avoids some of the ambiguity problems of multiple inheritance (diamond problem, or diamond inheritance)

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-91

Page 92: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Virtual Inheritance (example)class Animal {

public:

virtual void eat(); };

class Mammal : public Animal {

public:

virtual void walk(); };

class WingedAnimal : public Animal {

public:

virtual void flap(); };

// A bat is a winged mammal

class Bat : public Mammal, public WingedAnimal {...};

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-92

Page 93: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Virtual Inheritance (example)

int main(){

Bat bat;

bat.eat(); //ambiguous: requires either of the following!!

bat.WingedAnimal::eat();

bat.Mammal::eat();

return(0);}

Internally, inheritance is simply a matter of putting parent and child class one after the other in memory.

Thus a Bat object is stored as: (Animal,Mammal,Animal,WingedAnimal,Bat)

which makes Animal duplicated.

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-93

Page 94: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Virtual Inheritance solution

class Animal {

public:

virtual void eat(); };

class Mammal : public virtual Animal {

public:

virtual void walk(); };

class WingedAnimal : public virtual Animal {

public:

virtual void flap(); };

// A bat is still a winged mammal

class Bat : public Mammal, public WingedAnimal {};

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-94

Page 95: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Virtual Inheritance (example)

int main(){

Bat bat;

bat.eat(); //non-ambiguous!!

bat.WingedAnimal::eat(); //same as above

bat.Mammal::eat(); //same as above

return(0);}

Here, a Bat object is stored as: (*Animal,Mammal,*Animal,WingedAnimal,Bat)

Both *Animal are vtable pointers to the same Animal memory block

Thus, no ambiguity in this case.

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-95

Page 96: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-96

Summary 1

Inheritance provides code reuse Allows one class to "derive" from another,

adding features

Derived class objects inherit members ofbase class And may add members

Private member variables in base classcannot be accessed "by name" in derived

Private member functions are not inherited

Page 97: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-97

Summary 2

Can redefine inherited member functions To perform differently in derived class

Protected members in base class: Can be accessed "by name" in derived class

member functions

Overloaded assignment operator not inherited But can be invoked from derived class

Constructors are not inherited Are invoked from derived class’s constructor

Page 98: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-98

constructors

const qualifier

inline functions

static qualifier

Page 99: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-99

Learning Objectives

Constructors Definitions Calling

More Tools const parameter modifier Inline functions Static member data

Page 100: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-100

Constructors

Initialization of objects Initialize some or all member variables Other actions possible as well

A special kind of member function Automatically called when object declared

Very useful tool Key principle of OOP

Page 101: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-101

Constructor Definitions

Constructors defined like any member function

Except:

1. Must have same name as class

2. Cannot return a value; not even void!

Page 102: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-102

Constructor Definition Example

Class definition with constructor:

class DayOfYear{ public: //Constructor initializes month & day DayOfYear(int monthValue, int dayValue);

void input(); void output(); … private: int month; int day;}

Page 103: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-103

Constructor Notes

Notice name of constructor: DayOfYear Same name as class itself!

Constructor declaration has no return-type Not even void!

Constructor in public section It’s called when objects are declared If private, could never declare objects from the exterior!

Page 104: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-104

Calling Constructors

Declare objects:DayOfYear date1(7,4), date2(5,5);

Objects are created here Constructor is called Values in parentheses passed as arguments

to constructor Member variables month, day initialized:date1.month 7 date2.month 5date1.day 4 date2.day 5

Page 105: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-105

Constructor Equivalency

Consider:DayOfYear date1, date2;date1.DayOfYear(7, 4); // ILLEGAL!date2.DayOfYear(5, 5); // ILLEGAL!

Seemingly OK… CANNOT call constructors like other member functions!

Page 106: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-106

Constructor Code

Constructor definition is like all other member functions:

DayOfYear::DayOfYear(int newMonth, int newDay){

month = newMonth;day = newDay;

}

Note same name around :: Clearly identifies a constructor

Note no return type Just as in class definition

Page 107: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-107

Alternative Definition

Previous definition equivalent to:

DayOfYear::DayOfYear( int monthValue,int dayValue)

: month(monthValue), day(dayValue) {…}

Third line called "Initialization Section"

Body left empty

Preferable definition version

Page 108: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-108

Constructor Additional Purpose

Not just initialize data

Body doesn’t have to be empty In initializer version

Validate the data! Ensure only appropriate data is assigned to

class private member variables Powerful OOP principle

Page 109: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-109

Overloaded Constructors

Can overload constructors just like other functions

Recall: a signature consists of: Name of function Parameter list

Provide constructors for all possibleargument-lists Particularly "how many"

Page 110: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-110

Class with Constructors Example: Display 7.1 Class with Constructors (1 of 3)

Page 111: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-111

Class with Constructors Example: Display 7.1 Class with Constructors (2 of 3)

Page 112: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-112

Class with Constructors Example: Display 7.1 Class with Constructors (3 of 3)

Page 113: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-113

Constructor with No Arguments

Can be confusing

Standard functions with no arguments: Called with syntax: callMyFunction();

Including empty parentheses

Object declarations with no "initializers": DayOfYear date1; // This way! DayOfYear date(); // NO!

What is this really?

Page 114: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-114

Explicit Constructor Calls

Can also call constructor AGAIN After object declared

Recall: constructor was automatically called then

Can call via object’s name; standard memberfunction call

Convenient method of setting member variables

Method quite different from standard member function call

Page 115: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-115

Explicit Constructor Call Example

Such a call returns "anonymous object“, which can then be assigned

DayOfYear holiday(7, 4);

Constructor called at object’s declaration Now to "re-initialize":

holiday = DayOfYear(5, 5);

Explicit constructor call Returns new "anonymous object" Assigned back to current object

Page 116: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-116

Default Constructor

Defined as: constructor w/ no arguments

One should always be defined

Auto-Generated? Yes & No If no constructors AT ALL are defined Yes If any constructors are defined No

If no default constructor: Cannot declare: MyClass myObject;

With no initializers

Page 117: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-117

Class Type Member Variables

Class member variables can be any type

Including objects of other classes!

Type of class relationship Powerful OOP principle

Need special notation for constructors

So they can call "back" to member object’s constructor

Page 118: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-118

Class Member Variable Example: Display 7.3 A Class Member Variable (1 of 5)

Page 119: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-119

Class Member Variable Example: Display 7.3 A Class Member Variable (2 of 5)

Page 120: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-120

Class Member Variable Example: Display 7.3 A Class Member Variable (3 of 5)

Page 121: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-121

Class Member Variable Example: Display 7.3 A Class Member Variable (4 of 5)

Page 122: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-122

Class Member Variable Example: Display 7.3 A Class Member Variable (5 of 5)

Page 123: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-123

Parameter Passing Methods

Efficiency of parameter passing Call-by-value

Requires copy be made Overhead

Call-by-reference Placeholder for actual argument Most efficient method

Negligible difference for simple types For class types clear advantage

Call-by-reference desirable Especially for "large" data, like class types

Page 124: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-124

The const Parameter Modifier

Large data types (typically classes) Desirable to use pass-by-reference Even if function will not make modifications

Protect argument Use constant parameter

Also called constant call-by-reference parameter

Place keyword const before type Makes parameter "read-only" Attempts to modify result in compiler error

Page 125: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-125

Use of const

All-or-nothing

If no need for function modifications Protect parameter with const Protect ALL such parameters

This includes class member function parameters

Good practice, as it provides useful information

Page 126: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-126

Inline Functions

For non-member functions (free functions): Use keyword inline in function declaration

and function heading

For class member functions: Place implementation (code) for function IN

class definition automatically inline

Use for very short functions only

Code actually inserted in place of call Eliminates overhead More efficient, but only when short!

Page 127: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-127

Inline Member Functions

Member function definitions Typically defined separately, in different file Can be defined IN class definition

Makes function "in-line"

Again: use for very short functions only

More efficient If too long “code bloating”

Page 128: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-128

Static Members

Static member variables All objects of class "share" one copy One object changes it all see change

Useful for "tracking" How often a member function is called How many instances (objects) of a class exist at given time

Place keyword static before type Must be initialized outside of class definition, even if private Can only be initialize once, hence not in the constructor Initialization is expected in the same file where the class

declaration resides (not necessarily though)

Page 129: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-129

Static Functions

Member functions can be static If no access to object data needed And still "must" be member of the class Make it a static function

Can then be called outside class From non-class objects:

E.g., Server::getTurn(); As well as via class objects

Standard method: myObject.getTurn();

Can only use static data and functions!

Page 130: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-130

Static Members Example: Display 7.6 Static Members (1 of 4)

Page 131: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-131

Static Members Example: Display 7.6 Static Members (2 of 4)

Page 132: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-132

Static Members Example: Display 7.6 Static Members (3 of 4)

Page 133: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-133

Static Members Example: Display 7.6 Static Members (4 of 4)

Page 134: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-134

Nested classes

A class can be declared inside another class, either as public or private

If private, it can only be used inside of the outer class

If public, it can be used outside of the outer class as OuterClass::InnerClass

The inner class’ name is local to the outer class

Page 135: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-135

Nested classes

class Outerclas{ public: … private: class InnerClass { … }; …};

Page 136: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-136

Local classes

A class definition can also be defined inside a function definition, called a “local class”

Its name is local to the block where it is defined, e.g. the function definition block

Cannot contain static members, as it would not make much sense

Page 137: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Polymorphism in C++ Polymorphism enables one common interface with

different implementations Enables objects to act differently under different

circumstances. Ability of objects belonging to different classes to respond

to method calls of the same name, each one according to an appropriate type-specific behavior.

In cases where type can be inferred at compile time, polymorphism is static.

In cases where types cannot be inferred at compile time, polymorphism is dynamic, requiring run-time late binding or dynamic binding.

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-137

Page 138: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Static polymorphism

Function overloading Defining functions with the same name that have different

meanings depending on their parameters.

Inheritance with function redefinition Right function to call is determined by the type of object

involved in the call.

Operator overloading Defining operators that can act upon different types

Class and function templates Defining classes that embed elements of a variable type. Defining functions that act upon data of a variable type.

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-138

Page 139: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Dynamic polymorphism

Virtual member functions, used from pointers to objects Right function to call is determined by the type of object

being pointed to, calling the member function of the most specific class.

As we may be using a pointer to an object of a superclass, this requires dynamic (run-time) analysis.

Managed by a virtual method table (vtable).

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-139

Page 140: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-140

Summary 1

Constructors: automatic initialization of class data Called when objects are declared Constructor has same name as class

Default constructor has no parameters Should always be defined

Class member variables Can be objects of other classes

Require initialization-section

Page 141: Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345 Advanced

Copyright 2006 Pearson Addison-Wesley, 2008-2013 Joey Paquet 2-141

Summary 2

Constant call-by-reference parameters More efficient than call-by-value

Can inline very short function definitions Can improve efficiency

Static member variables Shared by all objects of a class