cs 215 401 fall 2014 n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
CS 215-401 Fall 2014 PowerPoint Presentation
Download Presentation
CS 215-401 Fall 2014

Loading in 2 Seconds...

play fullscreen
1 / 98

CS 215-401 Fall 2014 - PowerPoint PPT Presentation


  • 107 Views
  • Uploaded on

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.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'CS 215-401 Fall 2014' - jeremy-castro


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
cs 215 401 fall 2014

CS 215-401 Fall 2014

Lecture 11

Class Review, Inheritance, Polymorphism

Ismail Abumuhfouz

Slide modified from Link 1

programming concept evolution
Programming Concept Evolution
  • Unstructured
  • Procedural
  • Object-Oriented
procedural concept
Procedural Concept
  • The main program coordinates calls to procedures and hands over appropriate data as parameters.
object oriented concept
Object-Oriented Concept
  • Objects of the program interact by sending messages to each other
objects
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
oo perspective
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.

example object oriented code
Example Object Oriented Code

int area()

{

return width*length;

}

};

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;

}

object oriented programming languages
Object-Oriented Programming Languages
  • Characteristics of OOPL:
    • Encapsulation
    • Inheritance
    • Polymorphism
    • Overloading
  • OOPLs support :
    • Modular Programming
    • Ease of Development
    • Maintainability
c haracteristics of oopl
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 oldones
    • 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
v is ibi l i t y mo dif i e r s
VisibilityModifiers

Permissions for datamembers andmember functions:

private:Canonlybeaccessedbythatclass protected:Canbeaccessed bysubclasses public:Canbeaccessed byanyone

Classmembers areprivateby default Cannotbeappliedtothewholeclass:

ClassDefinitions

e x a m p le
Example

class Box

{

public:

// Class name

// Public members

section

// Private

members

section

private:

int weight;

// Notice

the semicolon

};

ClassDefinitions

e x a mpl e i n uml
ExampleinUML
  • Always3 sections
  • Name
  • Datamembers
  • Memberfunctions
  • Visibilitymodifiers
  • Public(+)
  • Private(-)
  • Protected(#)

ClassDefinitions

inl i n e m e th ods
InlineMethods

Amethodthatisimplementedinsidetheclassdefinitioniscalledaninline method.

Thecompilermaychoosetoexpandthebodyofthemethodatthepointofcall.

Thecompiledcodeexecutesfastersinceit avoidstheoverheadofafunction call.

Inlining canmakethecompiledcodelargerandmorecomplex(usuallynotdesirableproperties).

Useinlining onlyfor veryshortmethods. Never usethemwithloopsor recursivecalls.

c las s i n t e r f ace
ClassInterface

Usuallytheclass definitionis inaninterface(or header) file,andtheimplementationinan implementation(or source) file.

Interfacefilesusuallyhavea.hextension. Implementationfilescan havea.cpp,.c++, or.C. Thefilenamedoesnothavetomatchtheclassname.

A#includestatementisusedtoincludetheclass definitionintotheimplementationfile:

#include “myclass.h”

ClassDefinitions

f u l l y q ual if i e d n a m e s
FullyQualifiedNames

Usea#ifndef...#define...#endifintheheader filetoavoidincludingtheclassdefinitionmorethan once.

Methodsimplementedinthesourcefileuseafullyqualifiedfunction name.

Thisavoids conflictswithotherclasses thathaveamethod withthesamename.

Afullyqualifiednameconsistsoftheclassname,adoublecolon,andthemethodname:

... ClassName::methodName ...

ClassDefinitions

e x a m p le1
Example

box.c

#include “box.h”

box.h

#ifndef

#define

BOX_H BOX_H

Box::Box( int w )

{

weight = w;

}

class Box

{

public:

Box( int w );

int Box::getWeight(

{

return weight;

}

int getWeight(

) const;

) const

private: int weight;

};

#endif

ClassDefinitions

c o n s t r uc t o r s
Constructors

Constructors servetwopurposes:theycreateand initializean object

Aconstructor isamethodwiththesamenameas theclass, and does nothaveareturntype

Therearethreetypesof constructors:

Adefaultconstructortakesno arguments

Anordinaryconstructorhassomearguments

Acopyconstructorisusedtomakecopies(clone)

ClassDefinitions

c o p y c o n s t r uct or
CopyConstructor

Acopyconstructor isusedtomakeacopy of an objectvalue.

Ittakesaninstanceofthesameclassasaconstant referenceargument:

Box( const Box & b );

Acopyconstructorisoftencalledimplicitly,suchaswhen passingbyvalue:

a ); //

Copy

constructor

called.

doStuff(

ClassDefinitions

e x a m p le2
Example

class

Box {

public:

// Default

constructor

Box( )

{ weight

= 0; }

private: int weight;

};

ClassDefinitions

de s t r u c t ors
Destructors

Thedestructoris implicitlycalledwhenan objectisdeleted

Objectmayhavebeenexplicitlydeletedusingdelete

Anobjectcouldalso beautomaticallydeletedat theendof afunctioniftheobjectisstack-resident

Thedestructorisnever calleddirectly

Thedestructor isdefined usingatildefollowed by theclassnameandtakesnoarguments:

~Box( );

ClassDefinitions

d e s t r uct o r s c o n t
Destructorscont.

Thedestructor usuallydeletes any heap-resident memorytheobjectmay haveallocated:

class Storage { public:

Storage( int s ) { space = new int[s]; }

int & operator[]( int i )

{ return space[i]; }

~Storage( ) { delete [] space; } private:

int * space;

};

ClassDefinitions

t h e k e y w o r d this
Thekeywordthis

Everymethod has apointer namedthiswhich points totheobjectthemethodwasinvoked on

class Box {

public:

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

Box & doStuff( ) { this->weight = 73; return *this;

}

private: int weight;

};

ClassDefinitions

f r i e n ds
Friends

Aclasscanhavefriends thatareallowedtoaccess itsprivatedatamembers andfunctions:

class Box { public:

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

// Allow access for global function operator<<

friend ostream & operator<<( ostream & out );

// Allow class Crate to access weight

friend class Crate;

private: int weight;

};

ClassDefinitions

friend functions example
Friend Functions Example

#include <iostream>

usingnamespacestd;

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/

friend class example
Friend Class Example

#include <iostream>

usingnamespacestd;

class Square;

class Rectangle {

int width, height;

public:

int area ()

{return (width * height);}

void convert (Square a);

};

class Square {

friendclass 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;

}

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

more about friends
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.
class definition
Class Definition
  • Data Members
  • Can be of any type, built-in or user-defined
  • non-static data member
    • Each class object has its own copy
  • static data member
    • Acts as a global variable
    • One copy per class type, e.g. counter
static data member
Static Data Member

Rectangle r1;

Rectangle r2;

Rectangle r3;

class Rectangle

{

private:

int width;

int length;

static int count;

public:

void set(int w, int l);

int area();

}

count

r1

r2

width

length

width

length

width

length

r3

static data member1
Static Data Member

#include<iostream>

usingnamespacestd;

classBox{

public:

staticintobjectCount;

// 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++;

}

doubleVolume(){

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 Box

intBox::objectCount=0;

intmain(void){

BoxBox1(3.3,1.2,1.5);// Declare box1

BoxBox2(8.5,6.0,2.0);// Declare box2

// Print total number of objects.

cout<<"Total objects: "<<Box::objectCount<<endl;

return0;

}

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

inheritance concept
Inheritance Concept

class Rectangle{

private:

int numVertices;

float *xCoord, *yCoord;

public:

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

float area();

};

Polygon

Rectangle

Triangle

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();

};

inheritance concept1
Inheritance Concept

class Polygon{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

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

};

Polygon

Rectangle

Triangle

class Rectangle{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

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

float area();

};

class Rectangle : public Polygon{

public:

float area();

};

inheritance concept2
Inheritance Concept

class Polygon{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

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

};

Polygon

Rectangle

Triangle

class Triangle{

protected:

int numVertices;

float *xCoord, float *yCoord;

public:

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

float area();

};

class Triangle : public Polygon{

public:

float area();

};

inheritance concept3
Inheritance Concept

class Point{

protected:

int x, y;

public:

void set (int a, int b);

};

x

y

Point

Circle

3D-Point

x

y

r

x

y

z

class Circle : public Point{

private:

double r;

};

class 3D-Point: public Point{

private:

int z;

};

inheritance concept4
Inheritance Concept

Augmenting the original class

Specializing the original class

Polygon

Point

Rectangle

Triangle

Circle

3D-Point

real

imag

ComplexNumber

ImaginaryNumber

RealNumber

imag

real

why inheritance
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
define a class hierarchy
Define a Class Hierarchy
  • Syntax:

classDerivedClassName : access-levelBaseClassName

where

    • access-level specifies the type of derivation
      • private by default, or
      • public
  • Any class can serve as a base class
    • Thus a derived class can also be a base class
class derivation
Class Derivation

Point

class Point{

protected:

int x, y;

public:

void set (int a, int b);

};

3D-Point

Sphere

class 3D-Point : public Point{

private:

double z;

… …

};

class Sphere : public 3D-Point{

private:

double r;

… …

};

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

what to inherit
What to inherit?
  • In principle, every member of a base class is inherited by a derived class
    • just with different access permission
access control over the members
Two levels of access control over class members

class definition

inheritance type

Access Control Over the Members

class Point{

protected: int x, y;

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

};

class Circle : public Point{

… …

};

access rights of derived classes
Access Rights of Derived Classes

Type of Inheritance

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

Access Control

for Members

class derivation1
Class Derivation

class mother{

protected: int mProc;

public: int mPubl;

private: int mPriv;

};

class grandDaughter : public daughter {

private: double gPriv;

public: void gFoo ( );

};

private/protected/public

int main() {

/*….*/

}

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

private: double dPriv;

public: void mFoo ( );

};

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

private: double dPriv;

public: void dFoo ( );

};

void daughter :: dFoo ( ){

mPriv = 10; //error

mProc = 20;

};

what to inherit1
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 for
    • constructor and destructor
    • operator=() member
    • friends

Since all these functions are class-specific

constructor rules for derived classes
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;}

};

output:

A:default

B

B test(1);

constructor rules for derived classes1
Constructor Rules for Derived Classes

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

  • DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args )
  • { DerivedClass constructor body }

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;}

};

output:

A:parameter

C

C test(1);

define its own members
Define its Own Members

class Point{

protected:

int x, y;

public:

void set(int a, int b);

};

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

x

y

Point

x

y

r

class Circle{

protected:

int x, y;

private:

double r;

public:

void set(int a, int b);

void set_r(double c);

};

Circle

class Circle : public Point{

private:

double r;

public:

void set_r(double c);

};

even more
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;}

};

slide49

Access a Method

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(); };

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

slide50

Time

ExtTime

Putting Them Together

  • Time is the base class
  • ExtTime is the derived class with public inheritance
  • The derived class can
    • inherit all members from the base class, except the constructor
    • access all public and protected members of the base class
    • define its private data member
    • provide its own constructor
    • define its public member functions
    • override functions inherited from the base class
class time specification
classTime Specification

// SPECIFICATION FILE ( time.h)

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 ;

} ;

slide52

Class Interface Diagram

Timeclass

Set

Protected data:

hrs

mins

secs

Increment

Write

Time

Time

derived class exttime
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

} ;

slide54

Class Interface Diagram

ExtTimeclass

Set

Set

Protected data:

hrs

mins

secs

Increment

Increment

Write

Write

ExtTime

Time

ExtTime

Time

Private data:

zone

implementation of exttime
Implementation of ExtTime

ExtTime :: ExtTime ( )

{

zone = EST ;

}

Default Constructor

ExtTime et1;

et1

hrs = 0

mins = 0

secs = 0

zone = EST

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

implementation of exttime1

5000

hrs = 8

mins = 30

secs = 0

zone = EST

et2

6000

???

5000

Implementation of ExtTime

Another 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);

implementation of exttime2
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;

}

working with exttime
Working withExtTime

#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

}

inheritance summary
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

a b s t r ac t c lass e s
AbstractClasses

Anabstractclass(orabstract baseclass)isaclassthat containspure virtual methods.

Apurevirtualmethoddoesnothaveabody. Itisinsteadassignedanull value:

class Animal { public:

virtual void speak( ) = 0;

  • };
  • Abstractbaseclassescanonlybeused throughinheritance
  • Itisimpossibletocreateaninstanceof an abstractclass
abstract classes pure virtual functions
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 Functionvirtual 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

example
Example

Shape

virtual void draw()

Circle

Triangle

public void draw()

public void draw()

slide64
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; // Valid

Circle c; // error : variable of an abstract class

pure virtual functions summary
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
summary continued
Summary ..continued

It 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 { //Abstractpublic :virtual void draw() = 0;

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

class Rectangle : public Shape

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

polymorphism an introduction
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
dynamic binding
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
po l ymo r ph is m i n c
PolymorphisminC+

Allpolymorphism inC++isdoneusinginheritance; thereisnoconceptof aninterface

Asubclassisdeclared usingthenameof theclass, acolon,thevisibilityof theparentclass,andthenameof theparentclass:

public:

public:

int radius;

int x_pos; int y_pos;

};

};

v i r tu al a n d n o n v ir t u al ov e r r iding
VirtualandNon-VirtualOverriding

Overridingoccurswhenachildclasshasamethod withtheexactsametypesignatureasoneoftheparentclassmethods

Bindingis theprocessof decidingwhether to executetheparent'sversion or thechild'sversion of amethod

Thekeywordvirtualdetermineswhether staticbindingor dynamic bindingisused

virtualonlyappearsintheclassdefinition

Polymorphism

virtual functions
Virtual Functions
  • Virtual Functions overcome the problem of run time object determination
  • Keyword virtual instructsthe compiler to use late binding and delay the object interpretation
  • How ?
    • 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
a c las s h i e r ar c h y
AClassHierarchy

Consider thefollowingclasshierarchy:

class Animal {

public: virtual

};

void

speak(

)=0;

class Bird

: public

Animal {

public: virtual

voidspeak( )

}

{ cout <<

};

“twitter”;

Polymorphism

a c las s h i e r ar c h y c o n t
AClassHierarchycont.

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!”; }

};

Polymorphism

s t ati c b in d ing
StaticBinding
  • virtualisnotusedwhen declaringthemethod:
  • voidbark(){
  • cout << “can't bark”; }
  • Thedecisionismadeatcompiletimebased onthe typeofthevariable:
d yn a mi c b inding
DynamicBinding

virtualisusedto declarethemethod:

virtual void speak( ){

cout << “woof!”; }

Thebinding decisionismadeat run-timebased on thetypeoftheobject:

limi t at io ns
Limitations
  • Thevalidity of callingamethodis alwaysstatic. If amethodisnotdefinedinaclassor inheritedfromaparentclass, itcannotbecalled:
  • Overridingonlyworkswithheap-residentvalues:
m o r e l i mi ta t io n s
MoreLimitations

Childclassescannotchangethetypeof binding

Amethodthatis declaredvirtualinaparentclasswill alwaysbevirtualinachild class,evenifvirtualis notusedinthechildclass

Similarly,amethodthatisnotdeclaredvirtualin theparentclasscanneverbemadevirtualinthechild class

Anymethodthat iscalledfromaconstructor cannot beoverridden

Virtualmethodsareneverinlined

priv a t e a n d p r o t ec t e d i n h e r i t a n c e
PrivateandProtectedInheritance

Usuallyinheritanceispublic

Protectedinheritancechanges publicmembersintheparenttoprotectedinthechild

Privateinheritancechangespublicandprotected members toprivate

class Pig :

{

public:

protected Mammal

void oink(

) { cout

<< “Oink!”; }

// The speak

//

and bark methods

can only be

accessed

by child

classes.

};

Polymorphism

v ir t ua l d e s t r u c t o r s
VirtualDestructors

If anyvirtualmethodsareused, thedestructor should bevirtualtoensurethatboththeparentand child destructors arecalled

class Bird public: virtual

: public Animal {

~Bird( ) { cout <<

“bird

killed”; }

};

class Duck public: virtual virtual

: public

Bird {

<< “quack!”; }

}

void

speak(

) { cout

~Duck(

) { cout

<< “duck killed”;

};

polymorphism example
Polymorphism Example

Please check the following example of polymorphism

polymorphism summary
Polymorphism Summary:
  • When you use virtual functions, compiler store additional information about the types of object available and created
  • Polymorphism is supported at this additional overhead
  • Important :
    • virtual functions work only with pointers/references
    • Not with objects even if the function is virtual
    • If a class declares any virtual methods, the destructor of the class should be declared as virtual as well.
so f ar polymorphism
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

a r a t i o n al c l a s s
ARationalClass

Consider this classfor storingrationalnumbers:

class rational {

private: inttop; intbottom;

};

a n ad d f u n c t io n
Anaddfunction

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

constrational add( constrational & r ) const{ int

int

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

return rational( t, b );

}

Nowadditionworks:

a b e tt e r a d d f unct io n
ABetteraddFunction

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:

constrational operator+( constrational r) const& {

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

intb = bottom *r.bottom;

returnrational( t,b );

}

o p e ra t or ov e r lo ading
OperatorOverloading

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.

OperatorOverloading

ov e r lo a d e d o p e ra t o r s
OverloadedOperators

)

->

->* new delete

f unct i o n s an d m e th ods
FunctionsandMethods

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=mustbemethods.

If usedasI/Ooperators(as they usuallyare),>>and

<<mustbeglobal functions.

OperatorOverloading

b in a r y ar i t hm e ti c o p e r at o r s
BinaryArithmeticOperators

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:
  • constrational operator/( constrational &r)const;
b in a r y a r i t hm e ti c o ps c o n t
BinaryArithmeticOps.cont.

Subtraction as a method:

constrational operator-( constrational&r)const{

intt= top * r.bottom – bottom * r.top;

intb=bottom* r.bottom;

returnrational(t,b);

}

Multiplication as a global function:

constrational operator*( constrational & l, constrational & r )

{

return rational(l.numerator( )*r.numerator(),l.denominator( ) * r.denominator( ) );

}

c o mp ari so n o p e ra t o r s
ComparisonOperators

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

}

in c r e m en t a n d d ec r e m e nt
IncrementandDecrement

Can beprefixform (++i) or postfixform(i++).

Prefixformincrements andreturnsthenewvalue:

Postfixformincrementsbutreturnstheoriginal value:

int c = a++; // a = 7, c = 6

Prefixincrementfortherationalasamethod:

operator++( ) { bottom;

const rational top = top +

return

}

in c r e m en t a n d d ec r e m e n t co n t
IncrementandDecrementcont.

To distinguish postfix from prefix, the postfix version uses a dummy integer argument:

constrational operator++( int) { rational temp = *this;

bottom; temp;

top += return

}

const

rational

operator--(

int) {

rational

temp = *this;

bottom; temp;

top -= return

}

a ssi g nm e n t o p e r at o r
AssignmentOperator

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;

= r.bottom;

*this;

bottom return

}

a ssi g nm e n t o p e r at o r c o n t
AssignmentOperatorcont.
  • 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
  • Commonmistakes:
  • 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