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

Slides:



Advertisements
Similar presentations
1 class Rectangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept.
Advertisements

Inheritance and Composition (aka containment) Textbook Chapter –
1 Another Way to Define A Class - Inheritance. 2 Inheritance Concept Rectangle Triangle Polygon class Polygon { private: int width, length; public: void.
Object-Oriented PHP (1)
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
1 Chapter 6 Object-Oriented Software Development.
1 Introduction to C++ Programming Concept Basic C++ C++ Extension from C.
תכנות מונחה עצמים Object Oriented Programming (OOP) אתגר מחזור ב' Inheritence ( הורשה Inheritence ( הורשה ( השקפים מבוססים על שקפים של אליהו ברוטמן ומרינה.
1 Review: Two Programming Paradigms Structural (Procedural) Object-Oriented PROGRAM PROGRAM FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT.
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
1 Chapter 14-1 Object- Oriented Software Development Dale/Weems.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 12: Adding Functionality to Your Classes.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CMSC 202 Inheritance.
1 Chapter 14 Object- Oriented Software Development Dale/Weems.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Chapter 14 Object-Oriented Software Development Dale/Weems/Headington.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
1 Chapter 14 Object-Oriented Software Development Dale/Weems.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Chapter 10 Inheritance and Polymorphism
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
1 Lecture 6: Polymorphism - The fourth pillar of OOP -
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Chapter -6 Polymorphism
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 CSE Programming in C++. 2 Overview Sign roster list Syllabus and Course Policies Introduction to C++ About Lab 1 Fill Questionnaire.
1 Another way to define a class Inheritance..!!. 2 Why Inheritance ? Inheritance is a mechanism for building class types from existing class types defining.
1 Chapter 4: Another way to define a class Inheritance..!!
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Inheritance Concept Polygon Rectangle Triangle class Rectangle{
CMSC 202 Polymorphism.
Inheritance Saras M. Srivastava LEARN BY EXAMPLES PGT – Comp. Sc.
Inheritance CMSC 202, Version 4/02.
7. Inheritance and Polymorphism
Polymorphism.
Review: Two Programming Paradigms
Introduction to Classes
Introduction to Classes
Programming Techniques Course
UNIT I OBJECT ORIENTED PROGRAMMING FUNDAMENTALS
Chapter 14 Object-Oriented Software Development
Another way to define a class
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
C++ Object Oriented 1.
Lecture 6: Polymorphism
Presentation transcript:

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

2 Programming Concept Evolution Unstructured Procedural Object-Oriented

3 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.

4 Object-Oriented Concept Objects of the program interact by sending messages to each other

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

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.

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

8 Object-Oriented Programming Languages Characteristics of OOPL: –Encapsulation –Inheritance –Polymorphism –Overloading OOPLs support : –Modular Programming –Ease of Development –Maintainability

9 Characteristics of OOPL Encapsulation: C ombining 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: A bility 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: A bility for different objects to interpret functions differently. Overloading

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: ● publicclassA;//Don'tdothis! protectedclassB;//Orthis!

Class Definitions 3 Example classBox { public: //Classname //Publicmembers section private: //Privatememberssection intweight; }; //Noticethesemicolon Box(intw){weight=w;} intgetWeight()const{returnweight;}

Example in UML ● Class Definitions 4 Always 3 sections – Name – Data members – Member functions Visibility modifiers – Public (+) – Private (-) – Protected (#) ● Box -weight : int +getWeight() : int

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. ●

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”

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... ●

Class Definitions 8 Example ● box.h #ifndef #define BOX_H classBox { public: Box(intw); intgetWeight()const; private: intweight; }; #endif ● box.c #include“box.h” Box::Box(intw) { weight=w; } intBox::getWeight( { returnweight; } )const

Class Definitions 1212 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) ● ●

Class Definitions 1313 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(constBox&b); A copy constructor is often called implicitly, such as when passing by value: ● doStuff( a);//Copyconstructorcalled. Boxa;//Defaultconstructorgets //calledimplicitly,too.

Class Definitions 1414 Example classBox{ public: Box() //Defaultconstructor {weight=0;}=0;} private: intweight; }; Box(intw)//Ordinaryconstructor {weight=w;} Box(constBox&b)//Copyconstructor {weight=b.weight;}

Class Definitions 2 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();

Class Definitions 2323 Destructors cont. ● The destructor usually deletes any heap-resident memory the object may have allocated: classStorage{ public: Storage(ints){space=newint[s];} int&operator[](inti) {returnspace[i];} ~Storage(){delete[]space;} private: int*space; };

Class Definitions 2424 The keyword this ● Every method has a pointer named this which points to the object the method was invoked on classBox{ public: Box(intw):weight(w){} Box&doStuff(){ this->weight= 73; return*this; } private: intweight; };

Class Definitions 2626 Friends ● A class can have friends that are allowed to access its private data members and functions: classBox{ public: Box(intw):weight(w){} //Allowaccessforglobalfunctionoperator<< friendostream&operator<<(ostream&out); //AllowclassCratetoaccessweight friendclassCrate; private: intweight; };

Friend Functions Example #include 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:

Friend Class Example Source: #include 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; }

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.

28 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

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; width length width length width length r1 r3 r2 count

Static Data Member #include 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 Box int 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:

Inheritance

32 class Rectangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept Rectangle Triangle 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(); };

33 Rectangle Triangle Polygon class 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

34 Rectangle Triangle Polygon class 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

35 Inheritance Concept Point Circle3D-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; }; xyxy xyrxyr xyzxyz

36 Augmenting the original class Specializing the original class Inheritance Concept RealNumber ComplexNumber ImaginaryNumber Rectangle Triangle Polygon Point Circle real imag real imag 3D-Point

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

38 Define a Class Hierarchy Syntax: class DerivedClassName : access-level BaseClassName 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

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

40 What to inherit? In principle, every member of a base class is inherited by a derived class just with different access permission

41 Access Control Over the Members Two levels of access control over class members class definition inheritance type class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ … };

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 privateprotectedpublic private--- protectedprivateprotected publicprivateprotectedpublic Type of Inheritance Access Controlfor Members

43 class daughter : mother{ private: double dPriv; public: void mFoo ( ); }; Class Derivation class 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/public int main() { /*….*/ } class grandDaughter : public daughter { private: double gPriv; public: void gFoo ( ); };

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 for constructor and destructor operator=() member friends Since all these functions are class-specific

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:default B output:

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:parameter C output: DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args ) { DerivedClass constructor body }

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); }; xyxy xyrxyr 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

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

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

50 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 ExtTimeTime

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)

52 Class Interface Diagram Protected data: hrs mins secs Set Increment Write Time Time class

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

54 Class Interface Diagram Protected data: hrs mins secs ExtTime class Set Increment Write Time Set Increment Write ExtTime Private data: zone

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 = 0 mins = 0 secs = 0 zone = EST et1

56 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); hrs = 8 mins = 30 secs = 0 zone = EST et ???

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

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.Write ( ) ; // outputs 08:35:02 PST }

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

ABSTRACT CLASS

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: classAnimal{ public: virtualvoidspeak()=0; ● }; ● Abstract base classes can only be used through inheritance ● It is impossible to create an instance of an abstract class

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

63 Example Shape virtual void draw() Circle public void draw() Triangle public void draw()

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() - Abstract public : 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

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

66 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 { //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; }

Polymorphism

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

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

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; inty_pos; }; public: intradius; }; Class2DObject {Class { Circle:public2DObject

PolymorphismPolymorphism71 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 ● ● ●

72 Virtual Functions Virtual Functions overcome the problem of run time object determination Keyword virtual instructs the 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 Class Hierarchy ● Consider the following class hierarchy: classAnimal{ public: virtual }; voidspeak() = 0;) = 0; classBird:publicAnimal{ public: virtual void speak() } {cout<< }; “twitter”; PolymorphismPolymorphism73

PolymorphismPolymorphism74 A Class Hierarchy cont. classCat:publicMammal{ public: voidspeak(){cout<<“meow!”;} virtualvoidpurr(){cout<<“purrrrr”;} }; classDog:publicMammal{ public: virtualvoidspeak(){cout<<“woof!”;} voidbark(){cout<<“woof!”;} }; classMammal : public Animal{ public: virtualvoid speak(){ cout<<“can'tspeak”;} voidbark() { cout<<“can'tbark”; };

Static Binding virtual is not used when declaring the method: voidbark() { cout<< “can'tbark”;} The decision is made at compile time based on the type of the variable: Dog*d=new Dog(); Mammal* m = d ; d->bark() ; //woof m->bark(); // can't bark.

Dynamic Binding ● virtual is used to declare the method: virtualvoidspeak(){ 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!

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. Mammalm =*d; m.speak(); // can't Speak

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 ●

PolymorphismPolymorphism 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 ● ● classPig: { public: protectedMammal voidoink(){cout<<“Oink!”;} //Thespeak // andbarkmethodscanonlybe accessedbychildclasses. };

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 :publicAnimal{ ~Bird(){cout<< “birdkilled”;} }; class Duck public: virtual virtual :publicBird{ voidspeak(){cout <<“quack!”;} } ~Duck(){cout<<“duckkilled”; };

Polymorphism Example Please check the following example of polymorphismpolymorphism

82 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.

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

Overloading

Operator Overloading

A Rational Class ● Consider this class for storing rational numbers: classrational{ private: inttop; intbottom; }; public: rational(intt=0,intb=1) :top(t),bottom(b){} rational(constrational&r) :top(r.top),bottom(r.bottom){){} intnumerator()const{returntop;} intdenominator()const{returnbottom;}

An add function ● To implement addition with two rationals, the following could be added to the class definition: constrationaladd(constrational&r)const{ int int t=top*r.bottom+bottom*r.top; b=bottom*r.bottom; returnrational(t,b); } ● Now addition works: rationala(5,6); rationalb(2,3); rationalc=a.add(b);

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: co nstrationaloperator+(constrational r) const& { int t= top* r.bottom + bottom *r.top; int b=bottom * r.bottom; returnrational( t,b ); }

Operator Overloading89 ● 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 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. ● ● ●

Overloaded Operators ) -> ->* new delete +&+& -|-| *~*~ /!/! % && ^ || ++--<<>>,< <===!=>>== +=-=*=/=%=&= |=^=<<=>>=[][](

Operator Overloading91 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. ●

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;//Thisshouldbeimpossible Parameters are values or constant references. ● ● The operands should not be modified. Methods should be declared constant: constrational operator/(constrational &r)const;

Binary Arithmetic Ops. cont. ● Subtraction as a method: constrational operator-( const rational&r) const{ intt= top * r.bottom – bottom * r.top; intb= bottom* r.bottom; returnrational(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( ) ); }

Comparison Operators Work like the binary arithmetic operators, except these return a boolean. Equals and less-than as methods: b ool operator==(constrational&r)const { returntop*r.bottom==bottom*r.top; } booloperator<( { constrational &r)const *r.top; returntop*r.bottom<bottom }

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: intc=a++;//a=7,c=6 ● Prefix increment for the rational as a method: constrational top =top+ operator++(){ bottom; return } inta=5; intb=a++;//a=6,b=6

Increment and Decrement cont. ● To distinguish postfix from prefix, the postfix version uses a dummy integer argument: constrationaloperator++(int) { rationaltemp=*this; top+= return bottom; temp; } constrationaloperator--(int){ rationaltemp=*this; top-= return bottom; temp; }

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: ● ● constrational&operator=(constrational&r) { top=r.top; bottom return =r.bottom; *this; }

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