polymorphism and virtual functions. motivation polymorphism is one of the fundamental mechanisms...

31
Polymorphism and Virtual Functions

Upload: gwen-carr

Post on 13-Jan-2016

235 views

Category:

Documents


0 download

TRANSCRIPT

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

Polymorphism and Virtual Functions

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

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

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

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

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

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

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

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 drawc.draw(); //Calls Circle class’s draw

• So far, there is nothing new here yet…

Class diagram

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

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 cr.Center(); //redraw the circle in the new positionc.Center(); //redraw the rectangle in the new position

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

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 cr.Center(); //redraw the circle in the new positionc.Center(); //redraw the rectangle in the new position

What is the problem here??

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

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 cr.Center(); //redraw the circle in the new positionc.Center(); //redraw the rectangle in the new position

It will call the draw() in Figure!!

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

Show the Figure example

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

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 cr.Center(); //redraw the circle in the new positionc.Center(); //redraw the rectangle in the new position

One possible solution is To re-define the Center() function in each derived class.

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

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?

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

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

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

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; //legalFigure 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

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

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

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

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.

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

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

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

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??!!

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

Show the Figure example

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

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

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

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!

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

Show the Figure example with virtual functions

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

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!

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

Show the Things and Animals example and more!

Polymorphism turns out to be another tool for software reuse!

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

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?

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

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.

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

More Virtual Function Examples

• Please go through (compile and run) the examples in the textbook!

• Show a modified employee example

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

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, shouldnot be used

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

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;

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

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.

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

Abstract Base Classes• Pure virtual functions require no definition

– Forces all derived classes to define "theirown" 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 allit’s members!

• If derived class fails to define all pure’s:– It’s an abstract base class too

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

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)