98
An Equal Opportunity University CS 215-401 Fall 2014 Lecture 11 Class Review, Inheritance, Polymorphism Ismail Abumuhfouz Slide modified from Link 1

CS 215-401 Fall 2014

Embed Size (px)

DESCRIPTION

CS 215-401 Fall 2014. Lecture 11 Class Review, Inheritance, Polymorphism Ismail Abumuhfouz. Slide modified from Link 1. Programming Concept Evolution. Unstructured Procedural Object-Oriented. Procedural Concept. - PowerPoint PPT Presentation

Citation preview

Page 1: CS 215-401  Fall 2014

An Equal Opportunity University

CS 215-401 Fall 2014Lecture 11

Class Review, Inheritance, Polymorphism

Ismail Abumuhfouz

Slide modified from Link 1

Page 2: CS 215-401  Fall 2014

2

Programming Concept Evolution

• Unstructured• Procedural• Object-Oriented

Page 3: CS 215-401  Fall 2014

3

Procedural Concept

• The main program coordinates calls to procedures and hands over appropriate data as parameters.

Page 4: CS 215-401  Fall 2014

4

Object-Oriented Concept

• Objects of the program interact by sending messages to each other

Page 5: CS 215-401  Fall 2014

5

Objects An object is an encapsulation of both functions and data

• Objects are an Abstraction– represent real world entities– Classes are data types that define shared common properties or attributes– Objects are instances of a class

• Objects have State – have a value at a particular time

• Objects have Operations – associated set of operations called methods that describe how to carry out

operations

• Objects have Messages – request an object to carry out one of its operations by sending it a message– messages are the means by which we exchange data between objects

Page 6: CS 215-401  Fall 2014

6

OO Perspective

Let's look at the Rectangle through object oriented eyes:• Define a new type Rectangle (a class)

– Data• width, length

– Function• area()

• Create an instance of the class (an object)• Request the object for its area

In C++, rather than writing a procedure, we define a class that encapsulates the knowledge necessary to answer the question - here, what is the area of the rectangle.

Page 7: CS 215-401  Fall 2014

7

class Rectangle

{

private:

int width, length;

public:

Rectangle(int w, int l)

{

width = w;

length = l;

}

main(){

Rectangle rect(3, 5); cout << rect.area()<<endl;}

int area(){ return width*length;}

};

Example Object Oriented Code

Page 8: CS 215-401  Fall 2014

8

Object-Oriented Programming Languages

• Characteristics of OOPL:–Encapsulation– Inheritance –Polymorphism–Overloading

• OOPLs support :– Modular Programming– Ease of Development– Maintainability

Page 9: CS 215-401  Fall 2014

9

Characteristics of OOPL• Encapsulation: Combining data structure with actions

– Data structure: represents the properties, the state, or characteristics of objects– Actions: permissible behaviors that are controlled through the member functions

Data hiding: Process of making certain data inaccessible • Inheritance: Ability to derive new objects from old ones

– permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more general/base class

– ability to define a hierarchical relationship between objects

• Polymorphism: Ability for different objects to interpret functions differently.

• Overloading

Page 10: CS 215-401  Fall 2014

Class Definitions

Page 11: CS 215-401  Fall 2014

Class Definitions

2

Visibility Modifiers

● Permissions for data members and member functions:

private: Can only be accessed by that

class protected: Can be accessed by

subclasses public: Can be accessed by

anyone

●Class members are private by

default Cannot be applied to the whole

class:

public class A; // Don't do this!

protected class B; // Or this!

Page 12: CS 215-401  Fall 2014

Class Definitions

3

Example

class Box{

public:

// Class name

// Publicmembers

section

private: // Private members section

int weight;}; // Notice the semicolon

Box( int w ) { weight = w; }int getWeight( )

const{ return weight; }

Page 13: CS 215-401  Fall 2014

Example in UML

Class Definitions

4

Always 3 sections– Name– Data members– Member functions

Visibility modifiers– Public (+)– Private (-)– Protected (#)

Box

-weight : int+getWeight() : int

Page 14: CS 215-401  Fall 2014

5

Inline Methods

● A method that is implemented inside the class definition is called an inline method.

The compiler may choose to expand the body of the method at the point of call.

● The compiled code executes faster since it avoids the overhead of a function call.

Inlining can make the compiled code larger and more complex (usually not desirable properties).

●Use inlining only for very short methods.

Never use them with loops or recursive

calls.

Page 15: CS 215-401  Fall 2014

Class Definitions

6

Class Interface

● Usually the class definition is in an interface (or header) file, and the implementation in an implementation (or source) file.

●Interface files usually have a .h extension.

Implementation files can have a .cpp, .c++, or .C.

The filename does not have to match the class

name.

● A #include statement is used to include the class definition into the implementation file:

#include “myclass.h”

Page 16: CS 215-401  Fall 2014

Class Definitions

7

Fully Qualified Names

● Use a #ifndef ... #define ... #endif in the header file to avoid including the class definition more than once.

Methods implemented in the source file use a fully qualified function name.

● This avoids conflicts with other classes that have a method with the same name.

A fully qualified name consists of the class name, a double colon, and the method name:

... ClassName::methodName ...

Page 17: CS 215-401  Fall 2014

Class Definitions

8

Example

● box.h#ifndef#define

BOX_H BOX_H

class Box{public:Box( int w);int getWeight( ) const;

private: intweight;

};#endif

● box.c#include“box.h”Box::Box( int w ){

weight = w;}

int Box::getWeight({

returnweight;

}

) const

Page 18: CS 215-401  Fall 2014

Class Definitions

12

Constructors

● Constructors serve two purposes: they create and initialize an object

A constructor is a method with the same name as the class, and does not have a return type

There are three types of constructors:

● A default constructor takes no arguments

An ordinary constructor has some arguments

A copy constructor is used to make copies (clone)

Page 19: CS 215-401  Fall 2014

Class Definitions

13

Copy Constructor

● A copy constructor is used to make a copy of an object value.

● It takes an instance of the same class as a constant reference argument:

Box( const Box & b );

A copy constructor is often called implicitly, such as when passing by value:

doStuff( a ); // Copy constructor called.

Box a; // Default constructor gets// called implicitly, too.

Page 20: CS 215-401  Fall 2014

Class Definitions

14

Example

class Box {public:Box( ) // Default constructor{ weight = 0; }

private: intweight;};

Box( int w ) // Ordinary constructor

{ weight = w; }Box( const Box & b ) // Copy constructor

{ weight = b.weight; }

Page 21: CS 215-401  Fall 2014

Class Definitions

22

Destructors

● The destructor is implicitly called when an object is deleted

● Object may have been explicitly deleted using delete

An object could also be automatically deleted at the end of a function if the object is stack-resident

The destructor is never called directly

● The destructor is defined using a tilde followed by the class name and takes no arguments:

~Box( );

Page 22: CS 215-401  Fall 2014

Class Definitions

23

Destructors cont.

● The destructor usually deletes any heap-resident memory the object may have allocated:

class Storage

{ public:Storage(

int

s

)

{

space

=

new

int[s];

}int &

operator[](int i )

{returnspace[i];

}

~Storage( ) { delete []

space; } private:int * space;

};

Page 23: CS 215-401  Fall 2014

Class Definitions

24

The keyword this

● Every method has a pointer named this which points to the object the method was invoked on

class Box {public:Box( int w ) : weight( w ){ }

Box &doStuff( ) { this->weight

= 73; return *this;

}

private: intweight;

};

Page 24: CS 215-401  Fall 2014

Class Definitions

26

Friends

● A class can have friends that are allowed to access its private data members and functions:

classBox{ public:

Box(

int

w

)

:

weight(

w

)

{

}

// Allow access for global functionoperator<<friend ostream & operator<<( ostream & out);

// Allow class Crate to access weightfriend class Crate;

private: intweight;

};

Page 25: CS 215-401  Fall 2014

Friend Functions Example#include <iostream>using namespace std; class Rectangle { int width, height; public: Rectangle() {} Rectangle (int x, int y) : width(x), height(y) {} int area() {return width * height;} friend Rectangle duplicate (const Rectangle&);}; Rectangle duplicate (const Rectangle& param){ Rectangle res; res.width = param.width*2; res.height = param.height*2; return res;} int main () { Rectangle foo; Rectangle bar (2,3); foo = duplicate (bar); cout << foo.area() << '\n'; return 0;}

Source: http://www.cplusplus.com/doc/tutorial/inheritance/

Page 26: CS 215-401  Fall 2014

Friend Class Example

Source: http://www.cplusplus.com/doc/tutorial/inheritance/

#include <iostream>using namespace std; class Square; class Rectangle { int width, height; public: int area () {return (width * height);} void convert (Square a);}; class Square { friend class Rectangle; private: int side; public: Square (int a) : side(a) {}}; void Rectangle::convert (Square a) { width = a.side; height = a.side;} int main () { Rectangle rect; Square sqr (4); rect.convert(sqr); cout << rect.area(); return 0;}

Page 27: CS 215-401  Fall 2014

More About Friends

In the previous example:• Rectangle is considered a friend class by

Square, but Square is not considered a friend by Rectangle.

• Therefore, the member functions of Rectangle can access the protected and private members of Square but not the other way around.

• Of course, Square could also be declared friend of Rectangle, if needed, granting such an access.

Another property of friendships is that they are not transitive: The friend of a friend is not considered a friend unless explicitly specified.

Page 28: CS 215-401  Fall 2014

28

Class Definition

Data MembersCan be of any type, built-in or user-definednon-static data member

Each class object has its own copy

static data memberActs as a global variableOne copy per class type, e.g. counter

Page 29: CS 215-401  Fall 2014

29

class Rectangle

{

private:

int width;

int length;

static int count;

public:

void set(int w, int l);

int area();

}

Static Data Member

Rectangle r1;Rectangle r2;Rectangle r3;

widthlength

widthlength

widthlength

r1

r3

r2

count

Page 30: CS 215-401  Fall 2014

Static Data Member#include <iostream>using namespace std;class Box{ public: static int objectCount; // Constructor definition Box(double l=2.0, double b=2.0, double h=2.0){ cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // Increase every time object is created objectCount++; } double Volume(){ return length * breadth * height; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box};// Initialize static member of class Boxint Box::objectCount = 0;int main(void){ Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2  // Print total number of objects. cout << "Total objects: " << Box::objectCount << endl;  return 0;}

Source: http://www.tutorialspoint.com/cplusplus/cpp_static_members.htm

Page 31: CS 215-401  Fall 2014

Inheritance

Page 32: CS 215-401  Fall 2014

32

class Rectangle{

private:

int numVertices;

float *xCoord, *yCoord;

public:

void set(float *x, float *y, int nV);

float area();

};

Inheritance Concept

RectangleTriangle

Polygon

class Polygon{

private:

int numVertices;

float *xCoord, *yCoord;

public:

void set(float *x, float *y, int nV);

};

class Triangle{

private:

int numVertices;

float *xCoord, *yCoord;

public:

void set(float *x, float *y, int nV);

float area();

};

Page 33: CS 215-401  Fall 2014

33

RectangleTriangle

Polygonclass Polygon{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

void set(float *x, float *y, int nV);

};

class Rectangle : public Polygon{

public:

float area();

};

class Rectangle{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

void set(float *x, float *y, int nV);

float area();

};

Inheritance Concept

Page 34: CS 215-401  Fall 2014

34

RectangleTriangle

Polygonclass Polygon{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

void set(float *x, float *y, int nV);

};

class Triangle : public Polygon{

public:

float area();

};

class Triangle{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

void set(float *x, float *y, int nV);

float area();

};

Inheritance Concept

Page 35: CS 215-401  Fall 2014

35

Inheritance Concept

Point

Circle 3D-Point

class Point{

protected:

int x, y;

public:

void set (int a, int b);

};

class Circle : public Point{

private:

double r;

};

class 3D-Point: public Point{

private:

int z;

};

xy

xyr

xyz

Page 36: CS 215-401  Fall 2014

36

Augmenting the original class

Specializing the original class

Inheritance Concept

RealNumber

ComplexNumber

ImaginaryNumber

Rectangle Triangle

Polygon Point

Circle

realimag

real imag

3D-Point

Page 37: CS 215-401  Fall 2014

37

Why Inheritance ?

Inheritance is a mechanism for

building class types from existing class types

defining new class types to be a specialization augmentation

of existing types

Page 38: CS 215-401  Fall 2014

38

Define a Class Hierarchy

Syntax:class DerivedClassName : access-level BaseClassName

where access-level specifies the type of derivation

private by default, orpublic

Any class can serve as a base classThus a derived class can also be a base class

Page 39: CS 215-401  Fall 2014

39

Class Derivation

Point

3D-Point

class Point{

protected:

int x, y;

public:

void set (int a, int b);

};

class 3D-Point : public Point{

private:

double z;

… …

};

class Sphere : public 3D-Point{

private:

double r;

… …

};

Sphere

Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere

Page 40: CS 215-401  Fall 2014

40

What to inherit?

In principle, every member of a base class is inherited by a derived class

just with different access permission

Page 41: CS 215-401  Fall 2014

41

Access Control Over the Members

Two levels of access control over class members

class definitioninheritance type

base c lass / superc lass /pa ren t c lass

deriv ed c lass / subc lass /ch ild c lass

deriv

e fro

m

mem

bers

goe

s to

class Point{

protected: int x, y;

public: void set(int a, int b);

};

class Circle : public Point{

… …

};

Page 42: CS 215-401  Fall 2014

42

The type of inheritance defines the access level for the members of derived class that are inherited from the base class

Access Rights of Derived Classes

private protected public

private - - -

protected private protected protected

public private protected public

Type of Inheritance

Access Controlfor M

embers

Page 43: CS 215-401  Fall 2014

43

class daughter : --------- mother{

private: double dPriv;

public: void mFoo ( );

};

Class Derivationclass mother{

protected: int mProc;

public: int mPubl;

private: int mPriv;

};

class daughter : --------- mother{

private: double dPriv;

public: void dFoo ( );

};

void daughter :: dFoo ( ){

mPriv = 10; //error

mProc = 20;

};

private/protected/publicint main() {

/*….*/

}

class grandDaughter : public daughter {

private: double gPriv;

public: void gFoo ( );

};

Page 44: CS 215-401  Fall 2014

44

What to inherit?

In principle, every member of a base class is inherited by a derived class

just with different access permission

However, there are exceptions forconstructor and destructor operator=() member friends

Since all these functions are class-specific

Page 45: CS 215-401  Fall 2014

45

Constructor Rules for Derived Classes

The default constructor and the destructor of the base class are always called when a new object of a derived class is created or destroyed.

class A {

public:

A ( )

{cout<< “A:default”<<endl;}

A (int a)

{cout<<“A:parameter”<<endl;}

};

class B : public A

{

public:

B (int a)

{cout<<“B”<<endl;}

};

B test(1);A:defaultB

output:

Page 46: CS 215-401  Fall 2014

46

Constructor Rules for Derived Classes

You can also specify an constructor of the base class other than the default constructor

class A {

public:

A ( )

{cout<< “A:default”<<endl;}

A (int a)

{cout<<“A:parameter”<<endl;}

};

class C : public A {

public:

C (int a) : A(a)

{cout<<“C”<<endl;}

};

C test(1);A:parameterC

output:

DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args )

{ DerivedClass constructor body }

Page 47: CS 215-401  Fall 2014

47

Define its Own Members

Point

Circle

class Point{

protected:

int x, y;

public:

void set(int a, int b);

};

class Circle : public Point{

private:

double r;

public:

void set_r(double c);

};

xy

xyr

class Circle{

protected:

int x, y;

private:

double r;

public:

void set(int a, int b);

void set_r(double c);

};

The derived class can also define its own members, in addition to the members inherited from the base class

Page 48: CS 215-401  Fall 2014

48

Even more …

A derived class can override methods defined in its parent class.

With overriding, the method in the subclass has the identical signature to the method in the base class. a subclass implements its own version of a base class method.

class A {

protected:

int x, y;

public:

void print ()

{cout<<“From A”<<endl;}

};

class B : public A {

public:

void print ()

{cout<<“From B”<<endl;}

};

Page 49: CS 215-401  Fall 2014

49

class Point{

protected:

int x, y;

public:

void set(int a, int b)

{x=a; y=b;}

void foo ();

void print();

};

class Circle : public Point{

private: double r;

public:

void set (int a, int b, double c) {

Point :: set(a, b); //same name function call

r = c;

}

void print(); };

Access a Method

Circle C;

C.set(10,10,100); // from class Circle

C.foo (); // from base class Point

C.print(); // from class Circle

Point A;

A.set(30,50); // from base class Point

A.print(); // from base class Point

Page 50: CS 215-401  Fall 2014

50

Putting Them Together

Time is the base classExtTime is the derived class with public inheritanceThe derived class can

inherit all members from the base class, except the constructoraccess all public and protected members of the base classdefine its private data memberprovide its own constructordefine its public member functionsoverride functions inherited from the base class

ExtTime

Time

Page 51: CS 215-401  Fall 2014

51

class Time Specification

class Time{

public :

void Set ( int h, int m, int s ) ;void Increment ( ) ;void Write ( ) const ;Time ( int initH, int initM, int initS ) ; // constructor Time ( ) ; // default

constructor

protected :

int hrs ; int mins ; int secs ;

} ;

// SPECIFICATION FILE ( time.h)

Page 52: CS 215-401  Fall 2014

52

Class Interface Diagram

Protected data:

hrs

mins

secs

Set

Increment

Write

Time

Time

Time class

Page 53: CS 215-401  Fall 2014

53

Derived Class ExtTime // SPECIFICATION FILE ( exttime.h)

#include “time.h”

enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT } ;

class ExtTime : public Time // Time is the base class and use public inheritance

{ public :

void Set ( int h, int m, int s, ZoneType timeZone ) ;void Write ( ) const; //overridden

ExtTime (int initH, int initM, int initS, ZoneType initZone ) ; ExtTime (); // default constructor

private :ZoneType zone ; // added data member

} ;

Page 54: CS 215-401  Fall 2014

54

Class Interface Diagram

Protected data:

hrs

mins

secs

ExtTime class

Set

Increment

Write

Time

Time

Set

Increment

Write

ExtTime

ExtTime

Private data:zone

Page 55: CS 215-401  Fall 2014

55

Implementation of ExtTime

Default Constructor

ExtTime :: ExtTime ( ){

zone = EST ;}

The default constructor of base class, Time(), is automatically called, when an ExtTime object is created.

ExtTime et1;

hrs = 0mins = 0secs = 0zone = EST

et1

Page 56: CS 215-401  Fall 2014

56

Implementation of ExtTimeAnother Constructor

ExtTime :: ExtTime (int initH, int initM, int initS, ZoneType initZone) : Time (initH, initM, initS) // constructor initializer

{ zone = initZone ;}

ExtTime *et2 =

new ExtTime(8,30,0,EST);hrs = 8mins = 30secs = 0zone = EST

et2

5000

???

6000

5000

Page 57: CS 215-401  Fall 2014

57

Implementation of ExtTime

void ExtTime :: Set (int h, int m, int s, ZoneType timeZone) { Time :: Set (hours, minutes, seconds); // same name function call

zone = timeZone ;}

void ExtTime :: Write ( ) const // function overriding

{

string zoneString[8] =

{“EST”, “CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT”} ;

Time :: Write ( ) ;

cout <<‘ ‘<<zoneString[zone]<<endl;

}

Page 58: CS 215-401  Fall 2014

58

Working with ExtTime

#include “exttime.h”… …

int main() {

ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor

called

thatTime.Write( ) ; // outputs 00:00:00 EST

thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT

thisTime.Increment ( ) ;thisTime.Increment ( ) ;thisTime.Write ( ) ; // outputs 08:35:02 PST

}

Page 59: CS 215-401  Fall 2014

59

Inheritance Summary

Inheritance is a mechanism for defining new class types to be a specialization or an augmentation of existing types.

In principle, every member of a base class is inherited by a derived class with different access permissions, except for the constructors

Page 60: CS 215-401  Fall 2014

ABSTRACT CLASS

Page 61: CS 215-401  Fall 2014

Abstract Classes● An abstract class (or abstract base class) is a class

that contains pure virtual methods.

●A pure virtual method does not have a

body. It is instead assigned a null value:class

Animal{ public:

virtual

void

speak(

)

=

0;

};

● Abstract base classes can only be used through inheritance● It is impossible to create an instance of an

abstract class

Page 62: CS 215-401  Fall 2014

Abstract Classes & Pure Virtual Functions

Some classes exist logically but not physically.Example : Shape

Shape s; // Legal but silly..!! : “Shapeless shape”

Shape makes sense only as a base of some classes derived from it. Serves as a “category”Hence instantiation of such a class must be prevented

class Shape //Abstract { public : //Pure virtual Function virtual void draw() = 0;}

A class with one or more pure virtual functions is an Abstract Class

Objects of abstract class can’t be created

Shape s; // error : variable of an abstract class

Page 63: CS 215-401  Fall 2014

63

ExampleShape

virtual void draw()

Circle

public void draw()

Triangle

public void draw()

Page 64: CS 215-401  Fall 2014

64

A pure virtual function not defined in the derived class remains a pure virtual function.Hence derived class also becomes abstract

class Circle : public Shape { //No draw() - Abstractpublic :void print(){ cout << “I am a circle” << endl;}

class Rectangle : public Shape {public :void draw(){ // Override Shape::draw() cout << “Drawing Rectangle” << endl;}

Rectangle r; // ValidCircle c; // error : variable of an abstract class

Page 65: CS 215-401  Fall 2014

65

Pure virtual functions : Summary• Pure virtual functions are useful because they make

explicit the abstractness of a class• Tell both the user and the compiler how it was

intended to be used.• Note : It is a good idea to keep the common code as

close as possible to the root of you hierarchy

Page 66: CS 215-401  Fall 2014

66

Summary ..continuedIt is still possible to provide definition of a pure virtual function in the base class.The class still remains abstract and functions must be redefined in the derived classes, but a common piece of code can be kept there to facilitate reuse.In this case, they can not be declared inline

class Shape { //Abstract public : virtual void draw() = 0;};

// OK, not defined inline void Shape::draw(){ cout << “Shape" << endl;}

class Rectangle : public Shape

{ public : void draw(){ Shape::draw(); //Reuse cout <<“Rectangle”<< endl;}

Page 67: CS 215-401  Fall 2014

Polymorphism

Page 68: CS 215-401  Fall 2014

68

Polymorphism – An Introduction

noun, the quality or state of being able to assume different forms - Webster.

• An essential feature of an OO Language• It builds upon Inheritance.• Allows run-time interpretation of object type for a

given class hierarchy• Also Known as “Late Binding”• Implemented in C++ using virtual functions

Page 69: CS 215-401  Fall 2014

69

Dynamic Binding

• Is the run-time determination of which function to call for a particular object of a derived class based on the type of the argument

• Declaring a member function to be virtual instructs the compiler to generate code that guarantees dynamic binding

• Dynamic binding requires pass-by-reference

Page 70: CS 215-401  Fall 2014

Polymorphism in C+

● All polymorphism in C++ is done using inheritance; there is no concept of an interface

A subclass is declared using the name of the class, a colon, the visibility of the parent class, and the name of the parent class:

public:intx_pos; int

y_pos;};

public:int radius;

};

Class 2DObject { Class{

Circle : public 2DObject

Page 71: CS 215-401  Fall 2014

Polymorphism

71

Virtual and Non-Virtual Overriding

● Overriding occurs when a child class has a method with the exact same type signature as one of the parent class methods

Binding is the process of deciding whether to execute the parent's version or the child's version of a method

The keyword virtual determines whether static binding or dynamic binding is used

virtual only appears in the class definition

Page 72: CS 215-401  Fall 2014

72

Virtual Functions

Virtual Functions overcome the problem of run time object determinationKeyword virtual instructs the compiler to use late binding and delay the object interpretationHow ?

• Define a virtual function in the base class. The word virtual appears only in the base class

• If a base class declares a virtual function, it must implement that function, even if the body is empty

• Virtual function in base class stays virtual in all the derived classes

• It can be overridden in the derived classes• But, a derived class is not required to re-implement a

virtual function. If it does not, the base class version is used

Page 73: CS 215-401  Fall 2014

A Class Hierarchy

● Consider the following class hierarchy:class Animal {public: virtual};

void speak( ) = 0;

class Bird : public Animal {public: virtual void speak( )

}{ cout <<};

“twitter”;

Polymorphism

73

Page 74: CS 215-401  Fall 2014

Polymorphism

74

A Class Hierarchy cont.

class Cat : public Mammal { public:void speak( ) { cout << “meow!”; }virtual void purr( ) { cout <<“purrrrr”; }};

class Dog : public Mammal { public:virtual void speak( ) { cout <<“woof!”;}void bark( ) { cout << “woof!”; }};

class Mammal : public Animal {public: virtual void speak( ){ cout << “can't speak”;} void bark( ) { cout << “can't bark”; };

Page 75: CS 215-401  Fall 2014

Static Binding• virtual is not used when declaring the

method:void bark() {

cout << “can't bark”; }

• The decision is made at compile time based on the type of the variable:

Dog * d = new Dog( );Mammal * m = d ;d->bark() ; //woofm->bark(); // can't bark.

Page 76: CS 215-401  Fall 2014

Dynamic Binding

● virtual is used to declare the method:virtual void speak( ){

cout << “woof!”; }

The binding decision is made at run-time based on the type of the object:

d->speak(); // woof!

m->speak(); // woof!

Animal *a = d;a->speak ();// woof!

Page 77: CS 215-401  Fall 2014

Limitations• The validity of calling a method is always static.

If a method is not defined in a class or inherited from a parent class, it cannot be called:

• Overriding only works with heap-resident values:

Dog * d = new Dog( );Animal *a =d;d->bark( ); // woof!a->bark( );// Compile error, not allowed.

Mammal m =*d;m.speak(); // can't Speak

Page 78: CS 215-401  Fall 2014

More Limitations

● Child classes cannot change the type of binding● A method that is declared virtual in a parent class

will always be virtual in a child class, even if virtual is not used in the child class

Similarly, a method that is not declared virtual in the parent class can never be made virtual in the child class

● Any method that is called from a constructor cannot be overridden

Virtual methods are never inlined●

Page 79: CS 215-401  Fall 2014

Polymorphism

79

Private and Protected Inheritance

● Usually inheritance is public

Protected inheritance changes public members in the parent to protected in the child

Private inheritance changes public and protected members to private

class Pig :{

public:

protected Mammal

void oink( ) { cout << “Oink!”; }// The speak//

and bark methods can only beaccessed by child classes.

};

Page 80: CS 215-401  Fall 2014

Virtual Destructors

● If any virtual methods are used, the destructor should be virtual to ensure that both the parent and child destructors are called

class Bird public: virtual

: public Animal {

~Bird( ) { cout << “bird killed”; }};

class Duck public: virtual virtual

: public Bird {

void speak( ) { cout << “quack!”; }}~Duck( ) { cout << “duck killed”;

};

Page 81: CS 215-401  Fall 2014

Polymorphism Example

Please check the following example of polymorphism

Page 82: CS 215-401  Fall 2014

82

Polymorphism Summary:When you use virtual functions, compiler store additional information about the types of object available and createdPolymorphism is supported at this additional overheadImportant :

virtual functions work only with pointers/referencesNot with objects even if the function is virtualIf a class declares any virtual methods, the destructor of the class should be declared as virtual as well.

Page 83: CS 215-401  Fall 2014

83

So far, Polymorphism

Polymorphism is built upon class inheritance

It allows different versions of a function to be called in the same manner, with some overhead

Polymorphism is implemented with virtual functions, and requires pass-by-reference

Page 84: CS 215-401  Fall 2014

Overloading

Page 85: CS 215-401  Fall 2014

Operator Overloading

Page 86: CS 215-401  Fall 2014

A Rational Class

● Consider this class for storing rational numbers:

class rational {

private: int top; intbottom;};

public:rational( int t = 0, int b = 1 )

:top(

t ), bottom( b ) { }

rational( const rational & r ):top(

r.top ), bottom( r.bottom ) { }int numerator( ) const{

return top; }

int denominator( ) const { returnbottom;

}

Page 87: CS 215-401  Fall 2014

An add function

● To implement addition with two rationals, the following could be added to the class definition:

const rational add( const rational & r) const { int

intt = top * r.bottom + bottom * r.top; b = bottom * r.bottom;

return rational( t, b);

}● Now addition works:

rational a( 5, 6 );

rational b( 2, 3 );

rational c = a.add( b );

Page 88: CS 215-401  Fall 2014

A Better add Function

● The syntax of the add function could be better. It would be nicer (and make sense) to write:Rational c = a + b;

● Operator overloading makes this possible:const rational operator+( const rational r) const& { int t = top * r.bottom + bottom *r.top; int b = bottom * r.bottom; return rational( t,b );}

Page 89: CS 215-401  Fall 2014

Operator Overloading

89

Operator Overloading

● Operator overloading allows existing C++ operators to work with user-defined data types.

There are limits to this, however:●

● At least one operand must be a user-defined type. It is impossible to change the meaning of 2 + 2.

Cannot create new operators.

Cannot change precedence and associativity.

Don't change the meaning of an operator - operator+should always do something similar to addition.

Page 90: CS 215-401  Fall 2014

Overloaded Operators

)

-> ->* new delete

+

&

-

|

*

~

/

!

%

&&

^

||

++ -- << >> , <

<= == != > >= =

+= -= *= /= %= &=

|= ^= <<= >>= [ ] (

Page 91: CS 215-401  Fall 2014

Operator Overloading

91

Functions and Methods

● Operators can generally be overloaded as member functions or global functions.

● Unary operators can be methods with no arguments or global functions with one argument.

Binary operators can be methods with one argument or global functions with two arguments.

● Operators [], (), ->, and = must be methods.

If used as I/O operators (as they usually are), >> and<< must be global functions.

Page 92: CS 215-401  Fall 2014

Binary Arithmetic Operators

● The result should be a new value.

The return value should be constant so it cannot be the target of an assignment:(a+b) =b; // This should be impossible

Parameters are values or constant references.

• The operands should not be modified.

• Methods should be declared constant:const rational operator/( const rational &r) const;

Page 93: CS 215-401  Fall 2014

Binary Arithmetic Ops. cont.

●Subtraction as a method:const rational operator-( const rational &r) const{

int t= top * r.bottom – bottom * r.top; int b= bottom * r.bottom; return rational(t,b);}

●Multiplication as a global function:const rational operator*( const rational & l, const rational & r ){ return rational(l.numerator( )*r.numerator(),l.denominator( ) * r.denominator( ) );}

Page 94: CS 215-401  Fall 2014

Comparison Operators

Work like the binary arithmetic operators, except these return a boolean.

Equals and less-than as methods:

bool operator==( const rational & r ) const{

return top * r.bottom == bottom *r.top;

}bool operator<({

const rational & r ) const

*r.top;

return top * r.bottom < bottom}

Page 95: CS 215-401  Fall 2014

Increment and Decrement

● Can be prefix form (++i) or postfix form (i++).● Prefix form increments and returns the new

value:

● Postfix form increments but returns the original value:

int c = a++; // a = 7, c = 6● Prefix increment for the rational as a method:const

rational top = top

+

operator++( ){ bottom;

return}

int a = 5;int b = a++; // a = 6, b = 6

Page 96: CS 215-401  Fall 2014

Increment and Decrement cont.

● To distinguish postfix from prefix, the postfix version uses a dummy integer argument:const rational operator++( int) { rational temp = *this;

top += return

bottom; temp;

}

const rational operator--( int ) {rational temp = *this;top -= return

bottom; temp;

}

Page 97: CS 215-401  Fall 2014

Assignment Operator

● The right operand is copied to the left operand.

Should return a constant reference or a constant value to prevent a second assignment.

Assignment operator for rational as a method:

const rational & operator=( const rational & r ){

top = r.top;bottom return

= r.bottom;*this;

}

Page 98: CS 215-401  Fall 2014

Assignment Operator cont.

• The assignment operator will be provided by the compiler if the programmer doesn't write it

• The compiler version just copies the data members

• If the class has pointers to other values that should be copied, the programmer should write the assignment

• Common mistakes:

• Not returning a value

• Not handling self-assignment

• Simply copying pointers rather than making copies of the heap-resident values the object has pointers to