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

Similar documents
Polymorphism Part 1 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

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

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

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

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

Inheritance, Polymorphism and the Object Memory Model

Object Oriented Software Design II

Object Oriented Software Design II

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

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

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

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

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:

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

ECE 3574: Dynamic Polymorphism using Inheritance

Inheritance, and Polymorphism.

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

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

Data Structures and Other Objects Using C++

04-24/26 Discussion Notes

Inheritance, Polymorphism, and Interfaces

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

Lecture 5: Inheritance

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

Inheritance and Polymorphism

Instantiation of Template class

Java Object Oriented Design. CSC207 Fall 2014

15: Polymorphism & Virtual Functions

CS11 Introduction to C++ Fall Lecture 7

G52CPP C++ Programming Lecture 13

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

COEN244: Polymorphism

POLYMORPHISM. Phone : (02668) , URL :

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.

Increases Program Structure which results in greater reliability. Polymorphism

C++ Important Questions with Answers

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

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

Function Overloading

Object Oriented Design

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

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?

QUIZ. How could we disable the automatic creation of copyconstructors

Chapter 3 Function Overloading

Object-Oriented Programming (OOP) Fundamental Principles of OOP

QUIZ. How could we disable the automatic creation of copyconstructors

OBJECT ORIENTED PROGRAMMING USING C++

Dynamic Binding C++ Douglas C. Schmidt

Programming Languages: OO Paradigm, Polymorhism and Class Members

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

Object Oriented Programming: Inheritance Polymorphism

Introduction to Programming Using Java (98-388)

Object-Oriented Design (OOD) and C++

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

Data Abstraction. Hwansoo Han

Object Oriented Programming CS250

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

C++ Polymorphism. Systems Programming

CS-202 Introduction to Object Oriented Programming

Inheritance. Chapter 15 & additional topics

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Midterm Exam 5 April 20, 2015

INHERITANCE: EXTENDING CLASSES

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Lesson Plan. Subject: OBJECT ORIENTED PROGRAMMING USING C++ :15 weeks (From January, 2018 to April,2018)

Programming in C# Inheritance and Polymorphism

COMP6771 Advanced C++ Programming

Inheritance. Overview. Chapter 15 & additional topics. Inheritance Introduction. Three different kinds of inheritance

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

Programming, numerics and optimization

Absolute C++ Walter Savitch

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

G Programming Languages - Fall 2012

C++ Quick Guide. Advertisements

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

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

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Chapter 6 Introduction to Defining Classes

Fast Introduction to Object Oriented Programming and C++

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Object Oriented Programming. Solved MCQs - Part 2

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

CMSC202 Computer Science II for Majors

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.

Transcription:

Polymorphism Part 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 1 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. 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). Me The same message sent to many different types of objects takes on many forms - hence the term polymorphism. Teacher Mom 3 4 How? Class Hierarchy: Inheritance Abstract Class Virtual Functions How? Class Hierarchy: Inheritance Abstract Class Virtual Functions Base-class pointer Vehicle Car Car Boat BMW Ford Base-class pointer = derived class object (pointer) 5 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 { virtual void draw();... class circle: public shape { 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. 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. 9 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; 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 11 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 { 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 Early binding polymorphism Process of overloading members Late 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 Compile-Time Binding void sayhi(); sayhi(); void sayhi() { cout <<"Hello, cruel world!"<< endl; 17 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 { virtual void sayhi(); ; class Tinker : public TradePerson { virtual void sayhi(); ; class Tailor : public TradePerson { virtual void sayhi(); ; #endif TradePerson sayhi() 20 File TradePerson.cpp // TradePerson.cpp #include "TradePerson.h" void TradePerson::sayHi() { cout <<"Just hi"<< endl; void Tinker::sayHi() { cout <<"Hi, I tinker"<< endl; void Tailor::sayHi() { cout <<"Hi, I tailor"<< endl; Test Client 1 (1) // Polymorphism Demo #include "TradePerson.h" TradePerson* p; int which; do { cout <<"1 == TradePerson, 2 == Tinker, 3 == Tailor "; cin >> which; while ( which < 1 which > 3 ); 21 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; 23 Test Client 2 (1) // TestClient.cpp #include "TradePerson.h" #include <ctime> 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]; 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. 25 26 Test Client 3 (1) // TestClient.cpp Test Client 3 (2) #include "TradePerson.h" switch ( which ) { #include <ctime> case 1: meet( tradeperson ); break; void meet( TradePerson& person ) { case 2: meet( tinker ); break; person.sayhi(); case 3: meet( tailor ); break; srand( time(0) ); unsigned which, i; TradePerson tradeperson; Tinker tinker; Tailor tailor; for( i=0; i<10; i++ ) { which = 1 + rand()%3; 27 28 Inheriting virtual Methods class TradePerson { virtual void sayhi() { cout <<"Just hi"<< endl; ; class Tinker : public TradePerson { ; Tinker t; t.sayhi(); 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 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 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 { int i; virtual void f ( ); virtual void g( ); ; vptr i vtable[0] &f ( ) vtable[1] &g ( ) class A vtable class A { int i; virtual void f ( ); ; class B : public A { virtual void f ( ); // override f( ) virtual void g ( ); // define g () ; class A vtable[0] &f ( ) vtable[0] &f ( ) class A vtable vtable[1] &g ( ) 33 class B vtable 34 Virtual Ponters and Vtables class B { int data1; int data2; void m0( ); virtual void m1( ); virtual void m2( ); ; class D : public B { int data3; virtual void m1( ); ; B D Virtual Pointers and Vtables B object D object data1 data2 data3 vptr vptr vtable 0x7723 0x23b4 0x99a7 0x23b4 B::m0 B::m1 B::m2 D::m1 Entry Points 35 36

Vtable B b1; D d1; B* p; // p is set to b1 s or d1 s address p->m1(); // 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 37 38 Constructors Can Not Be virtual class C { virtual C(); //*** ERROR virtual C( int ); //***ERROR virtual ~C(); virtual void m(); ; 39 virtual Destructors (1) // Virtual Destructor class A { 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 { Z() { cout <<"Z()"<< endl; q = new char[5000]; ~Z() { cout <<"~Z()"<< endl; delete [] q; private: char* q; ; virtual Destructors (3) void f() { A* ptr; ptr = new Z(); delete ptr; for( unsigned i=0; i<3; i++ ) f(); 41 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. static Method Can Not Be virtual class C { static virtual void f(); //***ERROR static void g(); virtual void h(); ; 43 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 { C() { /* */ C( int x ) { /* */ ; void f( double d ) { /* */ void f( char c ) { /* */ C c1; C c2( 26 ); f( 3.14 ); f( 'z' ); // 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 class B { virtual void m() { cout <<"B::m"<< endl; ; class D : public B { virtual void m() { cout <<"D::m"<< endl; ; B* p; p = new D; p->m(); 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. Name Hiding (1) class B { void m( int x ) { cout << x << endl; ; class D : public B { void m() { cout << "Hi" << endl; ; D d1; d1.m(); // OK: D::m expects no arguments d1.m( 26 ); //***ERROR : D::m expects no arguments 49 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. Name Hiding (2) class B { virtual void m( int x ) { cout << x << endl; ; class D : public B { virtual void m() { cout << "Hi" << endl; ; D d1; d1.m(); d1.m( 26 ); //***ERROR D's m takes no arguments 51 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 ; 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 53 54

Pure virtual Methods class ABC { virtual void open() = 0; int getcount() const { return n; private: int n; ; class X : public ABC { virtual void open() { /* */ ; class Y : public ABC { ; ABC a1; //***ERROR X x1; Y y1; //***ERROR 55 Abstract Classes class Shape { protected: Shape virtual void draw( ) = 0; virtual ~Shape( ) { ; ; class Rectangle : 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; 57 Constructors of Abstract Classes (1) // Abstract Class Constructor class Shape { 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 { 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 { 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) Shape* s; s = new Square( 0, 0, 5 ); s->draw(); delete s; Abstract Base Classes class BasicFile { virtual void open() = 0; virtual void close() = 0; virtual void flush() = 0; ; class InFile : public BasicFile { virtual void open() { /* */ virtual void close() { /* */ virtual void flush() { /* */ ; 61 62 Virtual Base Classes Parent classes may have a common base class Fruit Fruit Virtual Base Classes Problem: Fruit has a stem data member Peach and plum each inherit a stem member from Fruit Peach Plum Peach Plum Nectarine inherits a stem member from each Stem Nectarine Stem Could resolve using the scope operator Plum::stem Peach::stem 63 64 Virtual Base Classes - Specification 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. 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. 65 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 Exercise Rewrite class Shape as an Abstract Base Class. Test the polymorphism again with classes Shape, Rectangle, and Circle. Draw UML diagrams before coding. BasicFile InFile 67 68