Polymorphism and Virtual Functions. Motivation Polymorphism is one of the fundamental mechanisms offered by OOP, and it is directly related to inheritance.

Slides:



Advertisements
Similar presentations
Object Oriented Programming
Advertisements

Chapter 15 Polymorphism and Virtual Functions. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Virtual Function.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2003 Pearson Education, Inc. Slide 1.
C++ Review. User Defined Types Built-in data types are simple. Specific problems may demand aggregate/more complex data types. – Ex: polygons, matrices,
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Polymorphism and Virtual Functions. class Ball : public Sphere.
OOP Etgar 2008 – Recitation 71 Object Oriented Programming Etgar 2008 Recitation 7.
12/08/08MET CS Fall Polymorphism 10. Polymorphism Goal: Goal: Create methods that can be invoked with all object types, base as well as.
PolymorphismCS-2303, C-Term Polymorphism Hugh C. Lauer Adjunct Professor (Slides include materials from The C Programming Language, 2 nd edition,
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
Virtual Functions Fall 2008 Dr. David A. Gaitros
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Chapter 15 Inheritance. Slide Overview 15.1 Inheritance Basics 15.2 Inheritance Details 15.3 Polymorphism.
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 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Polymorphism and Virtual Functions
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Chapter 15 Polymorphism and Virtual Functions. Learning Objectives Virtual Function Basics – Late binding – Implementing virtual functions – When to use.
Slide 1 Polymorphism and Virtual Functions. Slide 2 Learning Objectives  Virtual Function Basics  Late binding  Implementing virtual functions  When.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
C++ Review Classes and Object Oriented Programming Parasol Lab, Texas A&M University.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
CS212: Object Oriented Analysis and Design Lecture 15: Inheritance in C++ -II.
Polymorphism, Abstraction and Virtual Functions. In this slide, we introduce virtual functions and two complex and powerful uses for derived classes that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
1 Lecture 6: Polymorphism - The fourth pillar of OOP -
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Java Polymorphism. What we have learned Polymorphism is one of the three very powerful and useful mechanisms offered by OOP. What are the other two?
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.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Basic Concepts of OOP.  Object-Oriented Programming (OOP) is a type of programming added to php5 that makes building complex, modular and reusable web.
OBJECT ORIENTED PROGRAMMING. Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism.
Object-Oriented Programming: Polymorphism Chapter 10.
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
1 C++ Classes & Object Oriented Programming Overview & Terminology.
Learning Objectives Relationships Among Objects in an Inheritance Hierarchy. Invoking Base-class Functions from Derived Class Objects. Aiming Derived-Class.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Virtual Function and Polymorphism
CMSC 202 Polymorphism.
Polymorphism and Virtual Functions
Advanced Program Design with C++
7. Inheritance and Polymorphism
Polymorphism &Virtual Functions
OOP What is problem? Solution? OOP
Object-Oriented Programming & Design Lecture 18 Martin van Bommel
Polymorphism.
Inheritance and Run time Polymorphism
Polymorphism & Virtual Functions
Polymorphism and Virtual Functions
Polymorphism Lec
What is polymorphism?.
Learning Objectives Inheritance Virtual Function.
Polymorphism Polymorphism
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
VIRTUAL FUNCTIONS RITIKA SHARMA.
Java Programming Language
Lecture 6: Polymorphism
Presentation transcript:

Polymorphism and Virtual Functions

Motivation Polymorphism is one of the fundamental mechanisms offered by OOP, and it is directly related to inheritance. Polymorphism means that the same message (i.e., function calling) may produce different results (i.e., outputs) if it is sent to different types of objects. – In program, it means to associate many meanings to the same function. But, why is it important or useful? Here is an example (and a good one) from the textbook

Figures Example Let us assume we need to implement several kinds of figures (or shapes), including – Rectangles, circles, ovals, etc. Different figures have some common attributes and behaviors – Center and draw function – These can be encapsulated in a base (or super) class They also have different attributes and behaviors – Rectangle data: height, width, center point – Circle data: center point, radius – Different draw functions – These can be implemented with a number of derived classes

Figures Example Based on what we have learned from inheritance, to reduce the repeated coding and improve the efficiency, we can define a base (or super) class to enclose all the common attributes of those different figures. Let us call this parent-class: Figure All the other different shapes are then the derived classes of Figure. Class diagram

Figures Example To handle the drawing of different shapes, each derived class needs a different draw function So that when different shapes (objects) are created, we can call the correct drawing function: Rectangle r; Circle c; r.draw(); //Calls Rectangle class’s draw c.draw(); //Calls Circle class’s draw So far, there is nothing new here yet… Class diagram

Figures Example Now Let us assume there is another member function in the base class Figure – Center(). – What it does is to 1) erase the previous drawing, and 2) re-draw the shape when it is relocated to a different position (i.e., someone moves the center of the shape) – That said, Center() will need to call the draw() function to re-draw the shapes! Since the other derived classes do not re-define (or overwrite) this function. It is automatically inherited and applied to all the objects created by the derived classes. For instance, Rectangle r; Circle c; //reset the center of r // reset the center of c r.Center(); //redraw the circle in the new position c.Center(); //redraw the rectangle in the new position

Figures Example Now Let us assume there is another member function in the base class Figure – Center(). – What it does is to 1) erase the previous drawing, and 2) re-draw the shape when it is relocated to a different position (i.e. someone moves the center of the shape) – That said, Center() will need to call the draw() function to re-draw the shapes! Since the other derived classes do not re-define (or overwrite) this function. It is automatically inherited and applied to all the objects created by the derived classes. For instance, Rectangle r; Circle c; //reset the center of r // reset the center of c r.Center(); //redraw the circle in the new position c.Center(); //redraw the rectangle in the new position What is the problem here??

Figures Example Now Let us assume there is another member function in the base class Figure – Center(). – What it does is to 1) erase the previous drawing, and 2) re-draw the shape when it is relocated to a different position (i.e. someone moves the center of the shape) – That said, Center() will need to call the draw() function to re-draw the shapes! Since the other derived classes do not re-define (or overwrite) this function. It is automatically inherited and applied to all the objects created by the derived classes. For instance, Rectangle r; Circle c; //reset the center of r // reset the center of c r.Center(); //redraw the circle in the new position c.Center(); //redraw the rectangle in the new position It will call the draw() in Figure!!

Show the Figure example

Figures Example Now Let us assume there is another member function in the base class Figure – Center(). – What it does is to 1) erase the previous drawing, and 2) re-draw the shape when it is relocated to a different position (i.e. someone moves the center of the shape) – That said, Center() will need to call the draw() function to re-draw the shapes! Since the other derived classes do not re-define (or overwrite) this function. It is automatically inherited and applied to all the objects created by the derived classes. For instance, Rectangle r; Circle c; //reset the center of r // reset the center of c r.Center(); //redraw the circle in the new position c.Center(); //redraw the rectangle in the new position One possible solution is To re-define the Center() function in each derived class.

Figure Example Now, let us consider an outer function, i.e., user, that tries to use Figure and its derived classes to do something. From software reuse point of view, you want to keep the interface for calling Figure and its derived classes fixed! This is because the Figure may be used to derive many other new classes, such as Triangle, cylinder, hexagon, etc., you DO NOT WANT to create a new function each time you create a new derived class. This will be against the encapsulation principle. How to address that?

Figure Example Now, let us consider an outer function, i.e. user, that tries to use Figure and its derived classes to do something. From software reuse point of view, you want to keep the interface for calling Figure and its derived classes fixed! This is because the Figure may be used to derive many other new classes, such as Triangle, cylinder, hexagon, etc., you DO NOT WANT to create a new function each time you create a new derived class. This will be against the encapsulation principle. There is a rule that can help keep the interface unchanged – The objects of a derived class can be assigned to an object of the base class, but NOT VICE VERSA

Figure Example Circle c_obj (0.5, 0.3, 1.2); Rectangle r_obj (1.1, 1.4, 0.4, 0.6); Figure fig1 = c_obj; //legal Figure fig2 = r_obj; //legal Circle c_obj2 = fig1; //illegal The objects of a derived class can be assigned to an object of the base class, but NOT VICE VERSA

Figure Example Circle c_obj (0.5, 0.3, 1.2); Rectangle r_obj (1.1, 1.4, 0.4, 0.6); Figure *fig1 = &c_obj; Figure *fig2 = &r_obj; A more common way is to use base type of *pointers* to point to the objects of derived classes

Figure Example Now let us consider the following outer function void fun(Figure *fpt, float ncx, float ncy) { fpt->set_center(ncx, ncy); fpt->Center(); } The benefit of using this function as a wrapper is that no matter how many different derived classes are created later, the interface (i.e. the argument list) of calling this function NEED NOT CHANGE.

Figure Example Now let us consider the following outer function void fun(Figure *fpt, float ncx, float ncy) { fpt->set_center(ncx, ncy); fpt->Center(); } But a new problem arises Circle c_obj (0.5, 0.3, 1.2); Rectangle r_obj (1.1, 1.4, 0.4, 0.6); Figure *pt_figs[2]; pt_figs[0] = &c_obj; pt_figs[1] = &r_obj; fun(pt_figs[0], 0.1, 0.1); fun(pt_figs[1], 0.2, 0.2);

Figure Example Now let us consider the following outer function void fun(Figure *fpt, float ncx, float ncy) { fpt->set_center(ncx, ncy); fpt->Center(); } But a new problem arises Circle c_obj (0.5, 0.3, 1.2); Rectangle r_obj (1.1, 1.4, 0.4, 0.6); Figure *pt_figs[2]; pt_figs[0] = &c_obj; pt_figs[1] = &r_obj; fun(pt_figs[0], 0.1, 0.1); fun(pt_figs[1], 0.2, 0.2); pt_figs[0] points to a circle, while pt_figs[1] points to a rectangle. when entering the function fun(…), how does it know the right draw() function to call??!!

Show the Figure example

Figures Example: Virtual! Virtual functions are the answer A virtual function tells compiler: – "Don’t know how function is implemented" – "Wait until used in program" – "Then get implementation from object instance" Called “late binding” or “dynamic binding” – Virtual functions implement late binding

This is what we will do for the Figure example class Figure { public: Figure (float cx=0, float cy=0) {} virtual void draw(){…} void Center(){…} private: float center_x, center_y; }; class Circle : public Figure { public: Circle(float cx=0, float cy=0, float r=0) : Figure(cx, cy)),radius(r) {} virtual void draw() {new implementation for Circle} …… private: float radius; }; class Rectangle: public Figure { public: Rectangle(float cx=0, float cy=0, float w=0, float h=0) : Figure(cx, cy) {width=w; height=h;} virtual void draw() {new implementation for Rectangle} …… private: float radius; }; make the draw function virtual!

Show the Figure example with virtual functions

Polymorphism turns out to be another tool for software reuse! Now the function fun(…) can find the correct draw() and area() based on the types of the objects that the Figure type pointer points to!

Show the Things and Animals example and more! Polymorphism turns out to be another tool for software reuse!

Virtual destructor There is NO virtual constructor. There can have virtual destructor. They need not have the same name. Calling order: the destructor of the child class, then the destructor of the base class. class Base { public: Base(char * str) { my_str = new char[strlen(str)]; strcpy(my_str, str);} virtual ~Base(){delete [] my_str;} private: char * my_str; }; class Derived : public Base { public: Derived(char * str1, char * str2) : Base(str1) { dev_str2 = new char[strlen(str2)]; strcpy(dev_str2, str2);} virtual ~Derived() {delete [] dev_str2;} private: char * dev_str2; }; Why do we need virtual destructor?

Virtual destructor There is NO virtual constructor. There can have virtual destructor. There is no need to have the same name. Calling order: the destructor of the child class, then the destructor of the base class. class Base { public: Base(char * str) { my_str = new char[strlen(str)]; strcpy(my_str, str);} virtual ~Base(){delete [] my_str;} private: char * my_str; }; class Derived : public Base { public: Derived(char * str1, char * str2) : Base(str1) { dev_str2 = new char[strlen(str2)]; strcpy(dev_str2, str2);} virtual ~Derived() {delete [] dev_str2;} private: char * dev_str2; }; Derived d_obj (“hidden”, “I am derived.”); Base *b_pt = & d_obj; delete b_pt; if not virtual, the result of “delete” is uncertain.

More Virtual Function Examples Please go through (compile and run) the examples in the textbook! Show a modified employee example

Virtual Functions: Why Not All? Clear advantages to virtual functions as we’ve seen One major disadvantage: overhead! – Uses more storage – Late binding is "on the fly", so programs run slower So if virtual functions not needed, should not be used

Pure Virtual Functions Base class might not have "meaningful" definition for some of it’s members! – It’s purpose solely for others to derive from Recall the Figure examples – All figures are objects of derived classes Rectangles, circles, triangles, etc. – Class Figure has no idea how to draw! Make it a pure virtual function: virtual void draw() = 0;

class Figure { public: Figure (float cx=0, float cy=0) {} virtual void draw() = 0; // pure virtual function void Center(){…} private: float center_x, center_y; }; This requires the subsequent derived classes to provide implements for this function.

Abstract Base Classes Pure virtual functions require no definition – Forces all derived classes to define "their own" version Class with one or more pure virtual functions is: abstract base class – Can only be used as base class – No objects can ever be created from it Since it doesn’t have complete "definitions" of all it’s members! If derived class fails to define all pure’s: – It’s an abstract base class too

Different Polymorphisms Polymorphisms in object type conversion (explicit or implicit) Polymorphisms in function overloading Polymorphisms in function overwriting (via virtual function) Polymorphisms in template (will see)