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

Similar documents
OOP Fundamental Concepts

Polymorphism 8. Polymorphism. Content. Normal Member Functions Accessed with Pointers. Polymorphism. Virtual Members Abstract Class

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

Polymorphism Part 1 1

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

15: Polymorphism & Virtual Functions

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

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

Polymorphism. Zimmer CSCI 330

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

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

Object-Oriented Programming, Iouliia Skliarova

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

Inheritance, and Polymorphism.

Java Object Oriented Design. CSC207 Fall 2014

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

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

CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC

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

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

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

Data Structures and Other Objects Using C++

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

Programming, numerics and optimization

ECE 3574: Dynamic Polymorphism using Inheritance

Fast Introduction to Object Oriented Programming and C++

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

POLYMORPHISM. Phone : (02668) , URL :

04-24/26 Discussion Notes

1: Introduction to Object (1)

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:

Chapter 15. Polymorphism and Virtual Functions. Copyright 2010 Pearson Addison-Wesley. All rights reserved

C++ Programming: Polymorphism

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

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

VIRTUAL FUNCTIONS Chapter 10

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

Object Oriented Software Design II

Introduction to Design Patterns

What are the characteristics of Object Oriented programming language?

Object Oriented Software Design II

Object-Oriented Programming, Iouliia Skliarova

Composition I. composition is a way to combine or compose multiple classes together to create new class

CSCI 102 Fall 2010 Exam #1

Inheritance 6. Content. Inheritance. Reusability in Object-Oriented Programming. Inheritance

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

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

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

Content. Inheritance 6. Object Oriented Programming

COEN244: Class & function templates

Framework Fundamentals

Initializing and Finalizing Objects

CIS 190: C/C++ Programming. Lecture 11 Polymorphism

Object-Oriented Concept

void Transaction::print() { cout << "Name: " << name << " Amount: " << amount << endl; }

Inheritance, Polymorphism and the Object Memory Model


Instantiation of Template class

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Operator overloading

Object Oriented Programming: Inheritance Polymorphism

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

Chapter 1: Object-Oriented Programming Using C++

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

Syllabus of C++ Software for Hands-on Learning: This course offers the following modules: Module 1: Getting Started with C++ Programming

EECS 211 Lab 6. Classes and Abstractation Winter Getting the code. Encapsulation and Abstraction. Classes

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Inheritance. Program construction in C++ for Scientific Computing. School of Engineering Sciences. Introduction. Michael Hanke.

C++ (classes) Hwansoo Han

CS24 Week 3 Lecture 1

CS250 Final Review Questions

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

Object Oriented Programming in C#

Short Notes of CS201

Object-Oriented Programming

OBJECT ORIENTED PROGRAMMING

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Chapter 5 Object-Oriented Programming

University of Swaziland Department OfComputer Science Main Examination December 2016

CS11 Introduction to C++ Fall Lecture 7

CS201 - Introduction to Programming Glossary By

Virtual functions concepts

C++ Inheritance and Encapsulation

What does it mean by information hiding? What are the advantages of it? {5 Marks}

Object Oriented Programming in C++ Basics of OOP

Object Oriented Programming. Solved MCQs - Part 2

Ch. 11: References & the Copy-Constructor. - continued -

Data Structures using OOP C++ Lecture 3

Introduction to Programming

step is to see how C++ implements type polymorphism, and this Exploration starts you on that journey.

Object Oriented Programming COP3330 / CGS5409

Increases Program Structure which results in greater reliability. Polymorphism

VALLIAMMAI ENGINEERING COLLEGE

Chapter 16. Templates. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Pointers II. Class 31

Inheritance, Polymorphism, and Interfaces

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

Transcription:

1 License: http://creativecommons.org/licenses/by-nc-nd/3.0/ POLYMORPHISM There are three major concepts in object-oriented programming: 1. Encapsulation (Classes), Data abstraction, information hiding ( interface, private: implementation) 2. Inheritance, Is-a relation, generalization-specialization, reusability 3. Polymorphism Run-time decision for function calls (dynamic method binding) Polymorphism: In real life, there is often a collection of different objects that, given identical instructions (messages), should take different actions. Take teacher and principal, for example. Suppose the minister of education wants to send a directive to all personnel: Print your personal information!. Different kinds of staff (teacher or principal) have to print different information. But the minister doesn t need to send a different message to each group. One message works for everyone because everyone knows how to print his or her personal information. Besides the minister don t need to know the type of the person to whom the message is to be sent. 8.1 Polymorphism means taking many shapes. The minister s single instruction is polymorphic because it looks different to different kinds of personnel. The minister don t need to know the type of the person to whom she/he the message sends. Typically, polymorphism occurs in classes that are related by inheritance. In C++, polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that gets the message. The sender of the message don t need to know the type of the receiving object. This sounds a little like function overloading, but polymorphism is a different, and much more powerful, mechanism. One difference between overloading and polymorphism has to do with which function to execute when the choice is made. With function overloading, the choice is made by the compiler (compile-time). With polymorphism, it s made while the program is running (run-time). 8.2

2 Normal Member Functions Accessed with Pointers The first example shows what happens when a base class and derived classes all have functions with the same name and these functions are accessed using pointers but without using virtual functions (without polymorphism). class Teacher string name; int numofstudents; Teacher(const string &, int); void print() const; class Principal : public Teacher string SchoolName; Principal(const string &, int, const string &); void print() const; // Base class // Constructor of base // Derived class Both classes have a function with the same name: print. But in this example these functions are not virtual (not polymorphic). 8.3 // Show is a system that operates on Teachers and Principals void show (const Teacher * tp) The Principal class is derived from class Teacher. Both classes have a tp->print(); // which print member function with the same name print(). In main(), the program defines a // Only to test the show function pointer to class Teacher. int main() Teacher t1("teacher 1", 50); Principal p1("principal 1", 40, "School"); Teacher *ptr; char c; cout << "Teacher or Principal " ; cin >> c; if (c == 't') ptr = &t1; else ptr = &p1; show(ptr); // which print?? : Now the question is, when you execute the statement See Example: e81.cpp tp->print(); what function is called? Is it Teacher::print() or Principal::print()? The main program sometimes puts the address of the Teacher object and sometimes the address of a derived class object (Principal) in the base class pointer as in the line ptr = &p1; Remember that it s all right to assign an address of derived type to a pointer of the base. This address is sent to the function show() over a pointer to base. 8.4

3 The function in the base class (Teacher) is executed in both cases. The compiler ignores the contents of the pointer ptr and chooses the member function that matches the type of the pointer. Virtual Member Functions Accessed with Pointers Let s make a single change in the program: Place the keyword virtual in front of the declaration of the print() function in the base class. class Teacher string name; int numofstudents; Teacher(const string &, int); virtual void print() const; // Base class // Constructor of base // A virtual (polymorphic) function class Principal : public Teacher // Derived class string SchoolName; Principal(const string &, int, const string &); void print() const; // It is also virtual (polymorphic) See Example:e82.cpp 8.5 Now, different functions are executed, depending on the contents of ptr. Functions are called based on the contents of the pointer, not on the type. This is polymorphism at work. I ve made print() polymorphic by designating it virtual. Benefits of Polymorphism Polymorphism provides flexibility. In our example the show() function has no information about the type of object pointed by the input parameter. It can have the address of an object of any class derived from the Teacher class. So this function can operate on any class derived from the Teacher. If we add a new teacher type (a new class) to the system, for example InternTeacher, we do not need to change the show function. The same thing is true, if we discard a class derived from Teacher from the system. 8.6

4 License: http://creativecommons.org/licenses/by-nc-nd/3.0/ UML Diagram of the Design The Unified Modeling Language (UML) is explained in Chapter 9. This is only a simple example. Pointer tp in Show can point to objects of Teacher and to objects of all classes derived from Teacher. Show tp Teacher print() Inheritance Principal print() InternTeacher print() 8.7 Note that, in C++ it is preferred to use references instead of pointers by passing parameters. The same program can be written as follows: // Show is a system that operates on Teachers and Principals void show (const Teacher & tp) tp.print(); // which print // Only to test the show function int main() Teacher t1("teacher 1", 50); Principal p1("principal 1", 40, "School"); char c; cout << "Teacher or Principal " ; cin >> c; if (c == 't') show(t1); else show(p1); : 8.8

5 Late Binding How does the compiler know what function to compile? In e81.cpp, without polymorphism, the compiler has no problem with the expression tp->print(); It always compiles a call to the print() function in the base class. But in e82.cpp, the compiler doesn t know what class the contents of tp may be a pointer to. It could be the address of an object of the Teacher class or the Principal class. Which version of print() does the compiler call? In fact, at the time it s compiling the program, the compiler doesn t know which function to call. So instead of a simple function call, it places a piece of code there. At runtime, when the function call is executed, code that the compiler placed in the program finds out the type of the object whose address is in tp and calls the appropriate print() function: Teacher::print() or Principal::print(). Selecting a function at runtime is called late binding or dynamic binding. (Binding means connecting the function call to the function.) Connecting to functions in the normal way, during compilation, is called early binding or static binding. Late binding requires a small amount of overhead (the call to the function might take something like 10 percent longer) but provides an enormous increase in power and flexibility. 8.9 How It Works Remember that, stored in memory, a normal object that is, one with no virtual functions contains only its own data, nothing else. When a member function is called for such an object, the address of the object is available in the this pointer, which the member function uses (usually invisibly) to access the object s data. The address in this is generated by the compiler every time a member function is called; it s not stored in the object. With virtual functions, things are more complicated. When a derived class with virtual functions is specified, the compiler creates a table an array of function addresses called the virtual table. In the example e82.cpp, the Teacher and Principal classes each have their own virtual table. There is an entry in each virtual table for every virtual function in the class. Objects of classes with virtual functions contain a pointer to the virtual table (vptr) of the class. These object are slightly larger than normal objects. In the example, when a virtual function is called for an object of Teacher or Principal, the compiler, instead of specifying what function will be called, creates code that will first look at the object s virtual table and then uses this to access the appropriate member function address. Thus, for virtual functions, the object itself determines what function is called, rather than the compiler. 8.10

6 Example: Assume that the classes Teacher and Principal contain two virtual functions. class Teacher string name; int numofstudents; virtual void read(); virtual void print() const; class Principal : public Teacher string SchoolName; void read(); void print() const; // Base class // Virtual function // Virtual function // Derived class // Virtual function // Virtual function Virtual Table of Teacher &Teacher::read &Teacher::print Virtual Table of Principal &Principal::read &Principal::print 8.11 Objects of Teacher and Principal will contain a pointer to their virtual tables. int main() Teacher t1("teacher 1", 50); Teacher t2("teacher 2", 35); Principal p1("principal 1", 45, "School 1"); : Virtual Table of Teacher MC68000-like assembly counterpart of the statement ptr->print(); Here ptr contains the address of an object. move.l ptr, this ; this to object movea.l ptr, a0 ; a0 to object movea.l (a0), a1 ; a1<-vptr jsr 4(a1) ; jsr print If the print() function would not a virtual function: move.l ptr, this ; this to object jsr teacher_print or jsr principal_print t1 t2 p1 vptr Teacher 1 50 vptr Teacher 2 35 vptr Principal 1 45 School 1 &Teacher::read &Teacher::print Virtual Table of Principal &Principal::read &Principal::print 8.12

7 Don t Try This with Objects Be aware that the virtual function mechanism works only with pointers to objects and, with references, not with objects themselves. int main() Teacher t1("teacher 1", 50); Principal p1("principal 1", 40, "School"); t1.print(); p1.print(); return 0; License: http://creativecommons.org/licenses/by-nc-nd/3.0/ // not polymorphic // not polymorphic Calling virtual functions is a time-consuming process, because of indirect call via tables. Don t declare functions as virtual if it is not necessary. Linked List of Objects and Polymorphism The most common ways to use virtual functions are with an array of pointers to objects and linked lists of objects. Examine the example: See Example: e83.cpp Remember, there is a list class in the standard library of the C++. You don t need to write a class to define linked lists. 8.13 Abstract Classes To write polymorphic functions we need to have derived classes. But sometimes we don t need to create any base class objects, but only derived class objects. The base class exists only as a starting point for deriving other classes. This kind of base classes we can call an abstract class, which means that no actual objects will be created from it. Abstract classes arise in many situations. A factory can make a sports car or a truck or an ambulance, but it can t make a generic vehicle. The factory must know the details about what kind of vehicle to make before it can actually make one. Pure Virtual Functions It would be nice if, having decided to create an abstract base class, I could instruct the compiler to prevent any class user from ever making an object of that class. This would give me more freedom in designing the base class because I wouldn t need to plan for actual objects of the class, but only for data and functions that would be used by derived classes. There is a way to tell the compiler that a class is abstract: You define at least one pure virtual function in the class. A pure virtual function is a virtual function with no body. The body of the virtual function in the base class is removed, and the notation =0 is added to the function declaration. 8.14

8 class GenericShape protected: int x, y; A Graphics Example // Abstract base class GenericShape(int x_in, int y_in) x = x_in; y = y_in; // Constructor virtual void draw() const =0; // pure virtual function class Line:public GenericShape // Line class protected: int x2,y2; // End coordinates of line Line(int x_in,int y_in,int x2_in,int y2_in):genericshape(x_in,y_in), x2(x2_in),y2(y2_in) void draw()const; // virtual draw function void Line::draw()const cout << "Type: Line" << endl; cout << "Coordinates of end points: " << "X1=" << x << ",Y1=" << y << ",X2=" << x2 << ",Y2=" << y2 << endl; 8.15 class Rectangle:public GenericShape // Rectangle class protected: int x2,y2; // coordinates of 2nd corner point Rectangle(int x_in,int y_in,int x2_in,int y2_in):genericshape(x_in,y_in), x2(x2_in),y2(y2_in) void draw()const; // virtual draw void Rectangle::draw()const cout << "Type: Rectangle" << endl; cout << "Coordinates of corner points: " << "X1=" << x << ",Y1=" << y << ",X2=" << x2 << ",Y2=" << y2 << endl; class Circle:public GenericShape // Circle class protected: int radius; Circle(int x_cen,int y_cen,int r):genericshape(x_cen,y_cen), radius(r) void draw() const; // virtual draw 8.16

9 void Circle::draw()const cout << "Type: Circle" << endl; cout << "Coordinates of center point: " << "X=" << x << ",Y=" << y << endl; cout << "Radius: " << radius << endl; // A function to draw different shapes void show(const Generic_shape&shape) //Can take references to different shapes // Which draw function will be called? shape.draw(); // It 's unknown at compile-time int main() // A main function to test the system Line line1(1, 1, 100, 250); Circle circle1(100, 100, 20); Rectangle rectangle1(30, 50, 250, 140); Circle circle2(300, 170, 50); show(circle1); // show function can take different shapes as argument show(line1); show(circle2); show(rectangle1); return 0; See Example: e84a.cpp 8.17 UML Diagram of the Design Show shape GenericShape draw() Virtual class (italic) Pure virtual Function (italic) Line draw() Rectangle draw() Circle draw() Arc draw() 8.18

10 License: http://creativecommons.org/licenses/by-nc-nd/3.0/ If we write a class for a new shape by deriving it from an existing class, we don t need to modify the show function. This function can also show the new shape. For example we can add an Arc class to our graphics library, which will not effect the show function. class Arc:public Circle // Arc class protected: int sa, ea; // Start and end angles Arc(int x_cen,int y_cen,int r, int a1, int a2):circle(x_cen,y_cen,r), sa(a1),ea(a2) void draw() const; // virtual draw void Arc::draw()const See Example: e84b.cpp cout << "Type: Arc" << endl; cout << "Coordinates of center point: " << "X=" << x << ",Y=" << y << endl; cout << "Radius: " << radius << endl; cout << "Start and end angles: " << "SA=" << sa << ",EA=" << ea << endl; 8.19 Virtual Constructors? Can constructors be virtual? No, they can t be. When you re creating an object, you usually already know what kind of object you re creating and can specify this to the compiler. Thus, there s not a need for virtual constructors. Also, an object s constructor sets up its virtual mechanism (the virtual table) in the first place. You don t see the code for this, of course, just as you don t see the code that allocates memory for an object. Virtual functions can t even exist until the constructor has finished its job, so constructors can t be virtual. 8.20

11 See Example: e85.cpp Virtual Destructors Recall that a derived class object typically contains data from both the base class and the derived class. To ensure that such data is properly disposed of, it may be essential that destructors for both base and derived classes are called. But the output of e85.cpp is Base Destructor Program terminates In this program bp is a pointer of Base type. So it can point to objects of Base type and Derived type. In the example, bp points to an object of Derived class, but while deleting the pointer only the Base class destructor is called. This is the same problem you saw before with ordinary (nondestructor) functions. If a function isn t virtual, only the base class version of the function will be called when it s invoked using a base class pointer, even if the contents of the pointer is the address of a derived class object. Thus in e85.cpp, the Derived class destructor is never called. This could be a problem if this destructor did something important. To fix this problem, we have to make the base class destructor virtual. Rewrite: e85.cpp 8.21