Polymorphism Part 1 1

Similar documents
What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

C++ Programming: Polymorphism

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Polymorphism. Zimmer CSCI 330

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

VIRTUAL FUNCTIONS Chapter 10

Inheritance, and Polymorphism.

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

CS 162, Lecture 25: Exam II Review. 30 May 2018

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

Data type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:

15: Polymorphism & Virtual Functions

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Extending Classes (contd.) (Chapter 15) Questions:

POLYMORPHISM Polymorphism: the type Polymorphism taking many shapes type of object

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Object Oriented Software Design II

Inheritance, Polymorphism and the Object Memory Model

Object Oriented Software Design II

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Function Overloading

ECE 3574: Dynamic Polymorphism using Inheritance

OOP THROUGH C++(R16) int *x; float *f; char *c;

04-24/26 Discussion Notes

Increases Program Structure which results in greater reliability. Polymorphism

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

CS105 C++ Lecture 7. More on Classes, Inheritance

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Object-Oriented Programming, Iouliia Skliarova

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Midterm Exam 5 April 20, 2015

Instantiation of Template class

POLYMORPHISM. Phone : (02668) , URL :

Object Oriented Programming: Inheritance Polymorphism

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

G52CPP C++ Programming Lecture 13

Data Structures and Other Objects Using C++

Inheritance, Polymorphism, and Interfaces

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

Lecture 5: Inheritance

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

Inheritance and Polymorphism

Extending Classes (contd.) (Chapter 15) Questions:

Java Object Oriented Design. CSC207 Fall 2014

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

CS11 Introduction to C++ Fall Lecture 7

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

COEN244: Polymorphism

Fast Introduction to Object Oriented Programming and C++

OOP Fundamental Concepts

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.

Chapter 1: Object-Oriented Programming Using C++

C++ Important Questions with Answers

QUIZ. How could we disable the automatic creation of copyconstructors

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I.

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object-Oriented Design (OOD) and C++

QUIZ. How could we disable the automatic creation of copyconstructors

Lab Instructor : Jean Lai

Implementing an ADT with a Class

The Address-of Operator &: The & operator can find address occupied by a variable. If var is a variable then, &vargives the address of that variable.

Polymorphism. Contents. Assignment to Derived Class Object. Assignment to Base Class Object

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Object Oriented Design

C++ Polymorphism. Systems Programming

Computer Programming Inheritance 10 th Lecture

Object Oriented Programming in C++ Basics of OOP

Object-Oriented Programming

What are the characteristics of Object Oriented programming language?

CPSC 427: Object-Oriented Programming

Interview Questions of C++

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III

Chapter 3 Function Overloading

Friend Functions, Inheritance

C++ Quick Guide. Advertisements

CE221 Programming in C++ Part 1 Introduction

OBJECT ORIENTED PROGRAMMING USING C++

Dynamic Binding C++ Douglas C. Schmidt

Programming Languages: OO Paradigm, Polymorhism and Class Members

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Absolute C++ Walter Savitch

KLiC C++ Programming. (KLiC Certificate in C++ Programming)

Introduction to Programming Using Java (98-388)

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Data Abstraction. Hwansoo Han

Transcription:

Polymorphism Part 1 1

What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult 2

Why polymorphism? With polymorphism, one method can cause different actions to occur, depending on the type of the object on which the method is invoked. Me Teacher Mom 3

Quotes from Deitel & Deitel s The ability for objects of different classes related by inheritance to respond differently to the same message (i.e., member function call). The same message sent to many different types of objects takes on many forms - hence the term polymorphism. 4

How? Class Hierarchy: Inheritance Abstract Class Virtual Functions Base-class pointer Vehicle Car Boat Base-class pointer = derived class object (pointer) 5

How? Class Hierarchy: Inheritance Abstract Class Virtual Functions Car BMW Ford 6

Virtual Functions Virtual functions allow the programmer to declare functions in a base class that can be redefined in each derived class, class shape { public: virtual void draw();... class circle: public shape { public: virtual void draw();... 7

Declare a virtual function Pure virtual function Syntax 1 : virtual double earnings( ) = 0; Syntax 2 : virtual void print( ) const; A pure virtual function makes the corresponding class an abstract base class No objects of an abstract base class can be instantiated Classes from which objects can be instantiated are concrete classes. 8

More on Pure Virtual Function No definition given for pure virtual functions If a class is derived from a class with a pure virtual function, and if no definition is supplied for that pure virtual function in the derived class, then the virtual function remains pure in the derived class. Consequently, the derived class is also an abstract class. 9

Although we cannot instantiate objects of abstract base classes, we can declare pointers and references to abstract base classes. Such pointers and references can be used to enable polymorphic manipulations of derived-class objects Once a function is declared virtual, it remains virtual all the way down the inheritance hierarchy from that point, even if it is not declared virtual when a derived class overrides it. It is suggested to explicitly declare inherited virtual functions virtual at every level of the hierarchy. 10

Virtual Functions A virtual function must be declared in a parent class syntax virtual function virtual returntype functionname ( args i ) { function body ; pure virtual function virtual returntype functionname ( args i ) = 0; 11

Virtual Functions Declaration A function name is preceded by the keyword virtual Function name can only be used once in the parent class Cannot overload virtual functions Only class member functions can be declared virtual A function is virtual.. If it is declared virtual There is a base class function with the same signature declared virtual Any or all class member functions (except constructors) can be declared virtual 12

EXAMPLE 5.1.5. virtual void f( ); //*** ERROR: not a method int main ( ) { // Discussions: contains an error because it declares f, a top-level function rather than a method, to be virtual. 13

Example class C { public: virtual void m( ) ; // declaration--"virtual occurs //... ; void C::m( ) { // definition--"virtual" does not occur //... Discussions: virtual method m is defined outside the class declaration. Therefore, the keyword virtual occurs only in its declaration. 14

Derived class object to base class object conversion A derived class object is an object of its base class Base class object pointer = derived-class object A derived class object contains more features than its base-class Vehicle Note: the reverse is not true. BMW Car Boat Derived-class object pointer base-class object (pointer) Not enough information 15

Binding in C++ Polymorphism and C++ Early Binding occurs at compile time Late Early binding polymorphism Process of overloading members Binding occurs at runtime Late binding polymorphism The code to implement the method is chosen at runtime Appropriate code chosen sending a message to the object. Not to the pointer to the object Implemented through virtual functions 16

Compile-Time Binding vs. Run-Time Binding A function s name is associated with an entry point, the starting address of the code that implements the function Compile-time binding lets the compiler determines what code is to be executed when a function name is invoked Run-time binding is the binding of a function s name to an entry point when the program is running 17

Compile-Time Binding #include <iostream> using namespace std; void sayhi(); int main() { sayhi(); return 0; void sayhi() { cout <<"Hello, cruel world!"<< endl; 18

Requirements for C++ Polymorphism There must be an inheritance hierarchy The classes in the hierarchy must have a virtual method with the same signature There must be either a pointer or a reference to a base class. The pointer or reference is used to invoke a virtual method 19

File TradePerson.h // TradePerson.h #ifndef TRADE_PERSON_H #define TRADE_PERSON_H class TradePerson { public: virtual void sayhi(); ; class Tinker : public TradePerson { public: virtual void sayhi(); ; class Tailor : public TradePerson { public: virtual void sayhi(); ; #endif TradePerson sayhi() 20

File TradePerson.cpp // TradePerson.cpp #include "TradePerson.h" #include <iostream> using namespace std; void TradePerson::sayHi() { cout <<"Just hi"<< endl; void Tinker::sayHi() { cout <<"Hi, I tinker"<< endl; void Tailor::sayHi() { cout <<"Hi, I tailor"<< endl; 21

Test Client 1 (1) // Polymorphism Demo #include "TradePerson.h" #include <iostream> using namespace std; int main() { TradePerson* p; int which; do { cout <<"1 == TradePerson, 2 == Tinker, 3 == Tailor "; cin >> which; while ( which < 1 which > 3 ); 22

Test Client 1 (2) switch ( which ) { case 1: p = new TradePerson; break; case 2: p = new Tinker; break; case 3: p = new Tailor; break; p->sayhi(); delete p; return 0; 23

Test Client 2 (1) // TestClient.cpp #include "TradePerson.h" #include <iostream> #include <ctime> using namespace std; int main() { srand( time(0) ); TradePerson* ptr[10]; unsigned which, i; for( i=0; i<10; i++ ) { which = 1 + rand()%3; switch ( which ) { case 1: ptr[i] = new TradePerson; break; case 2: ptr[i] = new Tinker; break; case 3: ptr[i] = new Tailor; break; 24

Test Client 2 (2) for ( i=0; i<10; i++ ) { ptr[i]->sayhi(); delete ptr[i]; return 0; 25

The main function contains a call to srand( time ( 0 ) ); in order to avoid the generation of the same random numbers each time it runs. The keyword virtual must be explicitly declared in the base class. Any derived class method with the same signature will be automatically virtual. 26

Test Client 3 (1) // TestClient.cpp #include "TradePerson.h" #include <iostream> #include <ctime> using namespace std; void meet( TradePerson& person ) { person.sayhi(); int main() { srand( time(0) ); unsigned which, i; TradePerson tradeperson; Tinker tinker; Tailor tailor; for( i=0; i<10; i++ ) { which = 1 + rand()%3; 27

Test Client 3 (2) switch ( which ) { case 1: meet( tradeperson ); break; case 2: meet( tinker ); break; case 3: meet( tailor ); break; return 0; 28

Inheriting virtual Methods #include <iostream> using namespace std; class TradePerson { public: virtual void sayhi() { cout <<"Just hi"<< endl; ; class Tinker : public TradePerson { ; int main() { Tinker t; t.sayhi(); return 0; 29

Exercise Write a class Shape where a virtual method draw is defined as printing out a suitable message like Drawing Shape. Then finish classes Rectangle and Circle derived from Shape. Define the method draw in these two classes as displaying suitable messages like Drawing Rectangle and Drawing Circle. Try to test the polymorphism of these three classes in different ways. Draw UML diagrams before coding. 30

Virtual Functions When function in a class is declared virtual Keyword virtual tells compiler Don t perform early binding Install mechanisms to perform late binding Compiler responds by creating Table of function pointers Installing a data member to the class to point to the table 31

Virtual Functions The compiler created table is called the vtable (vtbl) Contains pointers to all functions declared virtual within the class and derived classes. Each class gets its own vtable A data member called the vpointer (vptr) Usually placed as the first element in object in memory. Initialized to the starting address of the vtable. The function call through a base class pointer Indexes into the vtable calls the function located at the address. 32

class A { public: int i; virtual void f ( ); virtual void g( ); ; vptr i vtable[0] &f ( ) vtable[1] &g ( ) class A vtable class A 33

class A { public: int i; virtual void f ( ); ; class B : public A { public: virtual void f ( ); // override f( ) virtual void g ( ); // define g () ; vtable[0] &f ( ) vtable[0] &f ( ) class A vtable vtable[1] &g ( ) class B vtable 34

Virtual Ponters and Vtables class B { public: int data1; int data2; void m0( ); virtual void m1( ); virtual void m2( ); ; class D : public B { public: int data3; virtual void m1( ); ; B D 35

Virtual Pointers and Vtables B object vptr vtable B::m0 data1 data2 0x7723 0x23b4 B::m1 B::m2 D object vptr data3 0x99a7 0x23b4 D::m1 Entry Points 36

Vtable int main() { B b1; D d1; B* p; // p is set to b1 s or d1 s address p->m1(); // 37

Run-Time Binding Using Vtable A program that uses run-time binding incurs a performance penalty in both space and time Pure object-oriented language incurs a relatively heavy penalty, because all functions are bound at run-time 38

Constructors Can Not Be virtual class C { public: virtual C(); //*** ERROR virtual C( int ); //***ERROR virtual ~C(); virtual void m(); ; 39

virtual Destructors (1) // Virtual Destructor #include <iostream> using namespace std; class A { public: A() { cout <<"A()"<< endl; p = new char[5]; virtual ~A() { cout <<"~A()"<< endl; delete [] p; private: char* p; ; 40

virtual Destructors (2) class Z : public A { public: Z() { cout <<"Z()"<< endl; q = new char[5000]; ~Z() { cout <<"~Z()"<< endl; delete [] q; private: char* q; ; 41

virtual Destructors (3) void f() { A* ptr; ptr = new Z(); delete ptr; int main() { for( unsigned i=0; i<3; i++ ) f(); return 0; 42

Exercise Write a class Diagram where a pointer shapes is used to maintain an array of Shape objects. In the constructor, shapes is newed as an array of two shape objects, one is a Rectangle object, and the other a Circle object. Try to write the destructor to delete shapes. Also, define a method draw to call the method draw of every element in the array pointed by shapes. Test your programs. Remember to draw UML. 43

static Method Can Not Be virtual class C { public: static virtual void f(); //***ERROR static void g(); virtual void h(); ; 44

Name Overloading Definition: Methods in the same class share the same name, but they have different formal parameter list. Name overloading always involves compile-time binding. 45

Name Overloading class C { public: C() { /* */ C( int x ) { /* */ ; void f( double d ) { /* */ void f( char c ) { /* */ int main() { C c1; C c2( 26 ); f( 3.14 ); f( 'z' ); // return 0; 46

Name Overriding Suppose that the base class B has a method m and its derived class D also has a method m with the same signature. If the methods are virtual, run-time binding is at work in any invocation of m through pointers or references. If the methods are virtual, the derived class method D : : m overrides the base class method B : : m. If the methods are not virtual, compile time binding is at work in any invocation of m. 47

Name Overriding #include <iostream> using namespace std; class B { public: virtual void m() { cout <<"B::m"<< endl; ; class D : public B { public: virtual void m() { cout <<"D::m"<< endl; ; int main() { B* p; p = new D; p->m(); return 0; 48

Name Hiding Suppose that base class B has a nonvirtual method m and its derived class D also has a method m. D s local method D : : m is said to hide the inherited method B : : m. Name hiding is particularly tricky if the derived class s method has a different signature than the base class s method of the same name. 49

Name Hiding (1) #include <iostream> using namespace std; class B { public: void m( int x ) { cout << x << endl; ; class D : public B { void m() { cout << "Hi" << endl; ; int main() { D d1; d1.m(); // OK: D::m expects no arguments d1.m( 26 ); //***ERROR : D::m expects no arguments return 0; 50

Discussions Slide 50 Example generates a fatal compile-time error because it tries to invoke D's method m with a single argument. D's base class B does have a method m that expects a single argument, and D inherits this method. The problem is that D has a method with the same name. Therefore, the local D: : m hides the inherited B: : m. To invoke the inherited m with an argument, we must amend the code to d1.b::m( 26 ); // OK: explicitly call B::m Name hiding can occur with virtual as well as nonvirtual methods. In effect, name hiding occurs with virtual methods whenever a derived class virtual method fails to override the base class virtual method. 51

Name Hiding (2) #include <iostream> using namespace std; class B { public: virtual void m( int x ) { cout << x << endl; ; class D : public B { virtual void m() { cout << "Hi" << endl; ; int main() { D d1; d1.m(); d1.m( 26 ); //***ERROR D's m takes no arguments return 0; 52

Discussions Slide 52 Example generates a fatal compiletime error. D s local method D : : m, which is virtual, hides the inherited method B : : m. One fix is to invoke B : : m explicitly d1.b : : m ; 53

Name Sharing Top-level functions with overloaded names Constructors with overloaded names Nonconstructor methods of the same class with the same name A derived class s local virtual method overrides a virtual method inherited from the base class For overriding to occur, the methods must be virtual and have the same signature 54

Pure virtual Methods class ABC { public: virtual void open() = 0; int getcount() const { return n; private: int n; ; class X : public ABC { public: virtual void open() { /* */ ; class Y : public ABC { ; ABC a1; //***ERROR X x1; Y y1; //***ERROR 55

Abstract Classes class Shape { protected: public: virtual void draw( ) = 0; virtual ~Shape( ) { ; ; class Rectangle : public Shape { public: Shape Rectangle void draw( ){ cout<< "Rectangle" <<endl; ~Rectangle( ) { ; 56

Using Abstract Classes void display( Shape& s ) { s.draw( ); int main() { Rectangle r; display( r ); Shape* shape = new Rectangle; shape->draw( ); delete shape; return 0; 57

Constructors of Abstract Classes (1) // Abstract Class Constructor #include <iostream> using namespace std; class Shape { public: Shape( int x0, int y0 ) { cout << "Shape constructor" << endl; xorigin = x0; yorigin = y0; virtual void draw() = 0; virtual ~Shape() { cout << "Destructing Shape" << endl; private: int xorigin; int yorigin; ; 58

Constructors of Abstract Classes (2) class Rectangle : public Shape { public: Rectangle( int x0, int y0, int size1, int size2 ) : Shape( x0, y0 ) { cout << "Rectangle constructor" << endl; this->size1 = size1; this->size2 = size2; void draw() { cout << "Drawing rectangle" << endl; ~Rectangle() { cout << "Destructing Rectangle" << endl; private: int size1; int size2; ; 59

Constructors of Abstract Classes (3) class Square : public Rectangle { public: Square( int x0, int y0, int size ) : Rectangle( x0, y0, size, size ) { cout << "Square constructor" << endl; virtual void draw() { cout << "Drawing Square" << endl; virtual ~Square() { cout << "Destructing Square" << endl; private: int size; ; 60

Constructors of Abstract Classes (4) int main() { Shape* s; s = new Square( 0, 0, 5 ); s->draw(); delete s; return 0; 61

Abstract Base Classes class BasicFile { public: virtual void open() = 0; virtual void close() = 0; virtual void flush() = 0; ; class InFile : public BasicFile { public: virtual void open() { /* */ virtual void close() { /* */ virtual void flush() { /* */ ; 62

Virtual Base Classes Parent classes may have a common base class Fruit Fruit Peach Plum Peach Plum Stem Stem Nectarine 63

Virtual Base Classes Problem: Fruit has a stem data member Peach and plum each inherit a stem member from Fruit Nectarine inherits a stem member from each Could resolve using the scope operator Plum::stem Peach::stem 64

Virtual Base Classes Solution: Declare Fruit as a virtual base class Result: Only a single copy of the base class in the derivation hierarchy. Only a single copy of all inherited data members. Subsequent derivations point to shared members. 65

Virtual Base Classes - Specification Syntax class DerivedClass : virtual accessspec BaseClass DerivedClass - The class being derived BaseClass - The parent class Specification - Specify base class member access public protected private The keyword virtual identifies BaseClass as a virtual base class of DerivedClass. 66

Interfaces An abstract base class specifies a shared interface The interface is shared by all classes derived from the abstract base class The interface is used to specify design requirement The interface promotes code reuse BasicFile InFile 67

Exercise Rewrite class Shape as an Abstract Base Class. Test the polymorphism again with classes Shape, Rectangle, and Circle. Draw UML diagrams before coding. 68