LECTURE 8. Polymorphism One interface, multiple methods C++ supports both compile time and runtime polymorphism.

Slides:



Advertisements
Similar presentations
Has-a Relationships A pen “has a” or “contains a” ball.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 15: Polymorphism,
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics (inheritance review + Java generics)
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics.
OOP Spring 2007 – Recitation 71 Object Oriented Programming Spring 2006 Recitation 8.
OOP Etgar 2008 – Recitation 71 Object Oriented Programming Etgar 2008 Recitation 7.
Inheritance, Polymorphism, and Virtual Functions
12/08/08MET CS Fall Polymorphism 10. Polymorphism Goal: Goal: Create methods that can be invoked with all object types, base as well as.
C++ Polymorphism Systems Programming. Systems Programming: Polymorphism 2   Polymorphism Examples   Relationships Among Objects in an Inheritance.
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.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
1 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Cpt S 122 – Data Structures Polymorphism
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 © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Object-Oriented Programming: Polymorphism 1. OBJECTIVES What polymorphism is, how it makes programming more convenient, and how it makes systems more.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
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.
TCP1201 OOPDS Lecture 4 1. Learning Objectives  To understand upcasting & downcasting  To understand static polymorphism and dynamic polymorphism 
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
Polymorphism and Virtual Functions. Topics Polymorphism Virtual Functions Pure Virtual Functions Abstract Base Classes Virtual Destructors V-Tables Run.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Object Oriented Programming
Class Relationships And Reuse Interlude 4 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
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.
Chapter -6 Polymorphism
OBJECT ORIENTED PROGRAMMING. Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 20 - Virtual Functions Outline 20.1Introduction 20.2Type Fields and switch Statements 20.3Virtual.
Polymorphism Lecture - 9.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
 2006 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
C++ How to Program, 7/e. © by Pearson Education, Inc. All Rights Reserved.2.
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
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,
CMSC 202 Polymorphism.
Polymorphism &Virtual Functions
Class A { public : Int x; A()
Object-Oriented Programming
Inheritance, Polymorphism, and Virtual Functions
Inheritance and Run time Polymorphism
Polymorphism & Virtual Functions
Polymorphism Lec
Virtual Functions Department of CSE, BUET Chapter 10.
Inheritance, Polymorphism, and Virtual Functions
Polymorphism CT1513.
Polymorphism Polymorphism
Programming II Polymorphism A.AlOsaimi.
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Polymorphism CMSC 202, Version 4/02.
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Computer Science II for Majors
Presentation transcript:

LECTURE 8

Polymorphism One interface, multiple methods C++ supports both compile time and runtime polymorphism

Example Situation That Needs Polymorphism How to write code that calls the appropriate version of draw() function with same function call? Answer: Polymorphism Shape class hierarchy Circle Right TriangleIsosceles Triangle TriangleRectangle Shape

Polymorphism Polymorphism is a feature of OOP that enables us to program in “general” rather than in “specific”. Polymorphism allows us to write programs that process the objects of classes that are part of the same class hierarchy as if they were all objects of the hierarchy’s base class

Polymorphism Polymorphism works with pointers Pointers of base class type are used to call appropriate member functions in objects of several derived classes This way you need to be concerned with only one type of pointers (i.e. base class pointers only) Helping feature: Virtual functions (later)

How Polymorphism Works? In the base class, create a virtual function Size() In the derived classes also, create appropriate definitions of Size() Create a base class pointer. During execution, if sptr points to a Rectangle type object, then call to Size() will execute Rectangle’s version of Size(). And if sptr points to a Circle type object, then call to Size() will execute Circle()’s version of Size().

How Polymorphism Works? Shape * sptr; sptr= new Rectangle(); sptr->Size();//Rectangle’s Size sptr=new Circle(); sptr->Size();//Circle’s Size // Notice the same call being used for different // functionalities // Important: the function Size() has to be virtual in // the base class

#include using namespace std; class Shape { public: virtual void size() { cout<<"size of shape\n"; } };

class Circle: public Shape { public: virtual void size() { cout<<"size of circle\n"; } }; class Rectangle: public Shape { public: virtual void size() { cout<<"size of rectangle\n"; } void otherFunction(){ cout<<"inside non-inherited function of derived class";} };

void main() { Shape * sptr; sptr= new Circle(); sptr->size(); sptr=new Rectangle(); sptr->size(); //following two cases are wrong //case 1:cannot call non-inherited derived class functions through //base class pointer (except by downcasting the pointer) //sptr->otherFunction(); //case 2: cannot assign base class address to derived class pointer //Circle * c; //c= new Shape(); }

Virtual Functions If size() was not virtual, which version would have been called? Answer: Shape’s version Without virtual functions, the type of the pointer determines which class’s functionality to invoke. With virtual function, the type of the object being pointed to, not the type of the pointer, determines which version of a virtual function to invoke Virtual functions are called through base-class pointer handles and base class reference handles, but not through name handles

Constructors and destructors Constructors cannot be virtual. Why?? Can we have virtual destructors. Why?? If a class has virtual functions, provide a virtual destructor even if one is not required for the class. This ensures that a custom derived-class destructor (if there is one) will be invoked when a derived-class object is deleted via a base class pointer

Dynamic vs. Static Binding If a program invokes a virtual function through a base class pointer to a derived class object, the program will choose the correct derived-class function dynamically (i.e. at execution time) based on the object type- not the pointer type. Choosing the appropriate function to call at execution time is called dynamic binding (or late binding)

Dynamic vs. Static Binding When a virtual function is called by referencing a specific object by name and using the dot operator, the function invocation is resolved at compile time (this is called static binding) and the virtual function that is called is the one defined for (or inherited by) the class of that particular object- this is not polymorphic behavior. Thus, dynamic binding with virtual functions occurs only through pointers.

Abstract Classes A class that cannot be instantiated Represents general features of its sub-classes; thus can act as stereo-types Can be used as a common interface to a hierarchy of classes

Abstract Classes Example CD player and DVD player Both involve an optical disk Operations Insert, remove, play, record, and stop such disks

Abstract Classes CDP and DVDP have an abstract base class GDP

Abstract Classes A class is made abstract by including at least one pure virtual function A pure virtual function does not have an implementation, and has a =0 in its signature A subclass of an abstract class is also abstract if it does not provide implementations for all the pure virtual functions in the superclass A class that has all its member functions pure virtual is called an interface

Abstract Base Class – Example in C++ class Shape // abstract base class { public: virtual void move(int dx, int dy) =0;// pure //virtual function virtual void show() const =0; // pure //virtual function };

Abstract Base Class – Example contd. class Circle : public Shape // concrete class { int xcenter,ycenter,radius; public: Circle(int xc, int yc, int r) : xcenter(xc), ycenter(yc), radius(r) {} void move(int dx, int dy) { xcenter += dx; ycenter += dy; } void show() const { cout <<"Circle centered at ("<<xcenter<<","<<ycenter<<") with radius " <<radius<<"."<<endl; } };

Abstract Base Class – Example contd. class Square : public Shape // concrete class { int xll,yll,xur,yur; public: Square(int x1, int y1, int x2, int y2) : xll(x1), yll(y1), xur(x2), yur(y2) {} void move(int dx, int dy) { xll += dx; yll += dy; xur += dx; yur += dy; } void show() const { cout <<"Square with lower left corner at ("<<xll<<","<<yll <<") and upper right corner at ("<<xur<<","<<yur<<")."<<endl; } };

Abstract Base Class – Example contd. void main() { // Shape s; // compiler error, Shape is abstract Circle c(10,20,5); Square s(0,0,15,10); Shape *array[2]={&c,&s}; cout <<"Before move:"<<endl; for (int i=0; i<2; i++) array[i]->show(); for (int i=0; i<2; i++) array[i]->move(5,-5); cout <<endl<<"After move:"<<endl; for (int i=0; i<2; i++) array[i]->show(); }