Computer Science Department Inheritance & Polymorphism.

Slides:



Advertisements
Similar presentations
CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
Advertisements

Inheritance & Dynamic Memory Allocation Suppose base class uses dynamic memory allocation. If derived class doesn’t use dynamic memory allocation then.
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.
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.
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
1 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Pointer Data Type and Pointer Variables
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
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.
Java and C++, The Difference An introduction Unit - 00.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
CS212: Object Oriented Analysis and Design Lecture 15: Inheritance in C++ -II.
Copyright 2006 Pearson Addison-Wesley, 2008, 2009, 2013 Joey Paquet 6-1 Concordia University Department of Computer Science and Software Engineering COMP345.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism and Virtual Functions. Topics Polymorphism Virtual Functions Pure Virtual Functions Abstract Base Classes Virtual Destructors V-Tables Run.
Chapter 10 Inheritance and Polymorphism
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
1 Lecture 6: Polymorphism - The fourth pillar of OOP -
Virtual FunctionstMyn1 Virtual Functions A virtual function is declared in a base class by using the keyword virtual. A function that you declare as virtual.
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.
CS212: Object Oriented Analysis and Design Lecture 16: Runtime Polymorphism.
Overview of C++ 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.
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.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
1 C++ Classes & Object Oriented Programming Overview & Terminology.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
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.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
CMSC 202 Polymorphism.
7. Inheritance and Polymorphism
Polymorphism &Virtual Functions
Polymorphism.
Inheritance and Run time Polymorphism
CS212: Object Oriented Analysis and Design
Inheritance & Polymorphism
Polymorphism & Virtual Functions
Polymorphism Lec
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Virtual Functions Department of CSE, BUET Chapter 10.
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.
CISC/CMPE320 - Prof. McLeod
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Overview of C++ Polymorphism
VIRTUAL FUNCTIONS RITIKA SHARMA.
Lecture 6: Polymorphism
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.
Presentation transcript:

Computer Science Department Inheritance & Polymorphism

Computer Science Department OOP Concepts Objects and Classes / Data Encapsulation Inheritance Polymorphism –Operator overloading is a kind of polymorphism CPS235:Polymorphism2

Computer Science Department Polymorphism A function/operator can behave differently depending on the context in which it is called We have already seen operator overloading in which a single ‘+’ operator behaves differently when used with floats, ints or strings Polymorphism refers to the ability of similar objects to respond differently to the same message i.e., the same type of function call Selecting the correct function is deferred until runtime and is based on the object CPS235:Polymorphism3

Computer Science Department Upcasting Inheritance represents an “is-a” relationship –The new class is a type of the existing class enum note { middleC, Csharp, Cflat }; class Instrument { public: void play(note) const {} }; // Wind objects are also Instruments class Wind : public Instrument {}; void tune(Instrument& i) { //... i.play(middleC); } int main() { Wind flute; tune(flute); // Upcasting } CPS235:Polymorphism4

Computer Science Department Upcasting (contd..) A Wind object is also an Instrument object, and there’s no function that tune( ) could call for an Instrument that isn’t also in Wind Inside tune( ), the code works for Instrument and anything derived from Instrument, and the act of converting a Wind object, reference, or pointer into an Instrument object, reference, or pointer is called upcasting CPS235:Polymorphism5

Computer Science Department Pointer and Reference Upcasting Wind w; Instrument* ip = &w; // Upcast Instrument& ir = w; // Upcast Of course, any upcast loses type information about an object. If you say Wind w; Instrument* ip = &w; the compiler can deal with ip only as an Instrument pointer and nothing else i.e., it cannot know that ip actually points to a Wind object So when you call the play( ) member function by saying ip->play(middleC); the compiler can know only that it’s calling play( ) for an Instrument pointer, and call the base-class version of Instrument::play( ) instead of what it should do, which is call Wind::play( ) CPS235:Polymorphism6

Computer Science Department Problem with upcasting enum note { middleC, Csharp, Cflat }; class Instrument { public: void play(note) const { cout << "Instrument::play" << endl; } }; class Wind : public Instrument { public: void play(note) const { cout << "Wind::play" << endl; } }; void tune(Instrument& i) { //... i.play(middleC); } int main() { Wind flute; tune(flute); // Upcasting } CPS235:Polymorphism7

Computer Science Department Problem with upcasting The output of the previous program is Instrument::play This is clearly not the desired output, because you know that the object is actually a Wind and not just an Instrument –The call should resolve to Wind::play The above discussion also applies if you use a pointer to an Instrument in the function tune CPS235:Polymorphism8

Computer Science Department Function call binding Connecting a function call to a function body is called binding When binding is performed before the program is run (by the compiler and linker), it’s called early binding or static binding The problem in the above program is caused by early binding because the compiler cannot know the correct function to call when it has only an Instrument address CPS235:Polymorphism9

Computer Science Department Dynamic Binding The solution to the above problem is called late binding or dynamic binding which means the binding occurs at runtime, based on the type of the object When a language implements late binding, there must be some mechanism to determine the type of the object at runtime and call the appropriate member function The compiler still doesn’t know the actual object type, but it inserts code that finds out and calls the correct function body Implemented in C++ using virtual functions CPS235:Polymorphism10

Computer Science Department Virtual Functions Virtual Functions enable run time object determination Keyword virtual instructs the compiler to use late binding and delay the object interpretation How ? –Define a virtual function in the base class. The word virtual appears only in the base class –If a base class declares a virtual function, it must implement that function, even if the body is empty –Virtual function in base class stays virtual in all the derived classes –It can be overridden in the derived classes But, a derived class is not required to re-implement a virtual function. If it does not, the base class version is used CPS235:Polymorphism11

Computer Science Department Virtual Functions enum note { middleC, Csharp, Cflat }; class Instrument { public: virtual void play(note) const { cout << "Instrument::play" << endl; } }; class Wind : public Instrument { public: void play(note) const { cout << "Wind::play" << endl; } }; void tune(Instrument& i) { //... i.play(middleC); } int main() { Wind flute; tune(flute); // prints Wind::play } CPS235:Polymorphism12

Computer Science Department Extensibility With play( ) defined as virtual in the base class, you can add as many new types as you want to the system without changing the tune( ) function Such a program is extensible because you can add new functionality by inheriting new data types from the common base class The functions that manipulate the base-class interface will not need to be changed at all to accommodate the new classes CPS235:Polymorphism13

Computer Science Department Extensibility enum note { middleC, Csharp, Cflat }; class Instrument { public: virtual void play(note) const { cout << "Instrument::play" << endl; } virtual char* what() const { return "Instrument"; } virtual void adjust(int) {} }; class Wind : public Instrument { public: void play(note) const { cout << "Wind::play" << endl; } char* what() const { return "Wind"; } void adjust(int) {} }; CPS235:Polymorphism14

Computer Science Department class Percussion : public Instrument { public: void play(note) const { cout << "Percussion::play" << endl; } char* what() const { return "Percussion"; } void adjust(int) {} }; class Stringed : public Instrument { public: void play(note) const { cout << "Stringed::play" << endl; } char* what() const { return "Stringed"; } void adjust(int) {} }; class Brass : public Wind { public: void play(note) const { cout << "Brass::play" << endl; } char* what() const { return "Brass"; } }; CPS235:Polymorphism15

Computer Science Department class Woodwind : public Wind { public: void play(note) const { cout << "Woodwind::play" << endl; } char* what() const { return "Woodwind"; } }; void tune(Instrument& i) { //... i.play(middleC); } int main() { Wind flute; Percussion drum; Stringed violin; Brass flugelhorn; Woodwind recorder; tune(flute); tune(drum); tune(violin); tune(flugelhorn); tune(recorder); } CPS235:Polymorphism16

Computer Science Department Virtual functions work only with addresses (references / pointers) class Base { public: virtual int f() const { return 1; } void g()const { cout<<“Base”; } }; class Derived : public Base { public: int f() const { return 2; } void show(){cout<<“derived only”; } void g() { cout<<“derived”; } }; CPS235:Polymorphism17

Computer Science Department Virtual functions work only with addresses (references / pointers) void main() { Derived d; Base* b1 = &d; Base& b2 = d; Base b3; // Late binding: cout f() = " f() << endl; cout << "b2.f() = " << b2.f() << endl; // Early binding: cout << "b3.f() = " << b3.f() << endl; cout g() = ” ; b1->g(); cout<<endl; cout show()=”; b1->show(); } CPS235:Polymorphism18

Computer Science Department Arrays of Pointers to Objects class Base { public: virtual void show() { cout<<"base“; } }; class Derv1 : public Base { public: void show() { cout<<"derv1“; }; class Derv2 : public Base { public: void show() { cout<<"derv2“; } }; void main() { Base* array[2]; Derv1 d1; Derv2 d2; array[0] = &d1; array[1] = &d2; for(int i=0;i<2;i++) array[i]->show(); getch(); } CPS235:Polymorphism19

Computer Science Department Object Slicing class Base { int i; public: Base(int ii = 0) : i(ii) {} virtual int sum() const { return i; } }; class Derived : public Base { int j; public: Derived(int ii = 0, int jj = 0): Base(ii),j(jj) {} int sum() const { return Base::sum() + j; }}; void call(Base b) { cout << "sum = " << b.sum() << endl; } int main() { Base b(10); Derived d(10, 47); call(b); call(d); } CPS235:Polymorphism20 If you use an object instead of a pointer or reference as the recipient of your upcast, the object is “sliced”

Computer Science Department Polymorphism Summary When you use virtual functions, compiler stores additional information about the types of object available and created Polymorphism is supported at this additional overhead Important : –virtual functions work only with pointers/references –Not with objects even if the function is virtual CPS235:Polymorphism21

Computer Science Department CPS235:Polymorphism22 Abstract Classes & Pure Virtual Functions Some classes exist logically but not physically. Example : Shape –Shape s; // Legal but silly..!! : “Shapeless shape” –Shape makes sense only as a base of some classes derived from it. Serves as a “category” –Hence instantiation of such a class must be prevented class Shape //Abstract { public : //Pure virtual Function virtual void draw() = 0; }  A class with one or more pure virtual functions is an Abstract Class  Objects of abstract class can’t be created Shape s; // error : variable of an abstract class

Computer Science Department CPS235:Polymorphism23 Example Shape virtual void draw() Circle public void draw() Triangle public void draw()

Computer Science Department CPS235:Polymorphism24 A pure virtual function not defined in the derived class remains a pure virtual function. Hence derived class also becomes abstract class Circle : public Shape { //No draw() - Abstract public : void print(){ cout << “I am a circle” << endl; } class Rectangle : public Shape { public : void draw(){ // Override Shape::draw() cout << “Drawing Rectangle” << endl; } Rectangle r; // Valid Circle c; // error : variable of an abstract class Abstract Classes & Pure Virtual Functions

Computer Science Department Abstract classes If a method is to be over-ridden by each child class, we can enforce this policy through the use of abstract classes You can’t create an object of an abstract class ( a class with at least one pure virtual function) You can also not pass or return an object of an abstract class by value CPS235:Polymorphism25

Computer Science Department CPS235:Polymorphism26 Abstract classes It is still possible to provide definition of a pure virtual function in the base class The class still remains abstract and functions must be redefined in the derived classes, but a common piece of code can be kept there to facilitate reuse class Shape { //Abstract public : virtual void draw() = 0; }; Shape::draw(){ cout << “Shape" << endl; } class Rectangle : public Shape { public : void draw(){ Shape::draw(); //Reuse cout <<“Rectangle”<< endl; }

Computer Science Department Virtual Destructor If any of the functions in your class are virtual, the destructor should be virtual as well class Base { public: virtual ~Base() { cout << "~Base()" << endl; } }; class Derived : public Base { public: ~Derived() { cout << "~Derived()" << endl; } }; int main() { Base* bp = new Derived; // Upcast delete bp; // Virtual destructor call } CPS235:Polymorphism27

Computer Science Department Things to remember Beginning a class method declaration with the keyword virtual in a base class makes the function virtual for the base class and all derived classes, classes further derived from derived classes, and so on… dynamic binding is possible only for a base class pointer or reference to an object of the derived class All those functions of the base class that need to be over- ridden in the derived classes should be made virtual Constructors cannot be virtual Destructors can be virtual –You should provide a base class which has virtual functions with a virtual destructor even if the class does not need a destructor (i.e., it does not contain dynamic data) CPS235:Polymorphism28

Computer Science Department Things to remember friends can’t be virtual since they are not member functions If a derived class does not redefine a virtual function, the base class version is used. If there is a chain of derived classes, then the most recently defined version of the virtual function is used An abstract class demands that its pure virtual functions must be over-ridden in each derived class, otherwise the derived class also becomes abstract CPS235:Polymorphism29

Computer Science Department Inheritance and Dynamic Memory Allocation If a base class uses dynamic memory allocation and redefines assignment operator and copy constructor, how does it affect the implementation of the derived class? –If the derived class does not itself use dynamic memory allocation, no special steps need to be taken –If the derived class uses dynamic memory allocation, then the assignment operator and copy constructor need to be defined for the derived class as well CPS235:Polymorphism30

Computer Science Department If the derived class does not use new class base { private: char* label; int rating; public: base(const char* l = "null",int r = 0); base(const base& rs); virtual ~base(); base& operator = (const base& rs); }; class lacksDMA : public base { private: char color[40]; public:... }; CPS235:Polymorphism31

Computer Science Department If the derived class does not use new There’s no need for defining a destructor. The default destructor will automatically call the base class destructor which will free the memory allocated in the base part of the object There’s no need for defining a copy constructor since the default copy constructor will automatically call the base class copy constructor for copying the base part of the object Assignment operator overloading is also not required for the same reason CPS235:Polymorphism32

Computer Science Department If the derived class does use new class hasDMA : public base { private: char* style; //to point to dynamic memory public:... }; For this class, you will have to define destructor, copy constructor and assignment operator CPS235:Polymorphism33

Computer Science Department If the derived class uses new Destructor base::~base() { delete [] label; } hasDMA::~hasDMA() { delete[] style; } CPS235:Polymorphism34

Computer Science Department If the derived class uses new Copy Constructor base::base(const base& rs) { label = new char[strlen(rs.label)+1]; strcpy(label,rs.label); rating = rs.rating; } hasDMA::hasDMA(const hasDMA& hs) : base(hs) { style = new char[strlen(hs.style)+1]; strcpy(style,hs.style); } CPS235:Polymorphism35

Computer Science Department If the derived class uses new Assignment Operator base& base::operator=(const base& rs) { if(this==&rs) return *this; delete [] label; label = new char[strlen(rs.label)+1]; strcpy(label,rs.label); rating = rs.rating; return *this; } hasDMA& hasDMA::operator=(const hasDMA& hs) { if(this==&hs) return *this; base::operator=(hs); //copy base style = new char[strlen(hs.style)+1]; strcpy(style,hs.style); return *this; } CPS235:Polymorphism36

Computer Science Department stream operators ostream& operator<<(ostream& os,const base& rs) //declared friend in class base { os<<"Label: " <<rs.label << endl; os << "Rating: " << rs.rating << endl; return os; } ostream& operator<<(ostream& os,const lacksDMA& rs)//declared friend in lacksDMA { os << (const base& )rs; //type casting //lacksDMA parameter to base argument os << "Color: " <<rs.color << endl; return os; } CPS235:Polymorphism37

Computer Science Department stream operators ostream& operator<< (ostream& os, const hasDMA& rs) //declared friend in hasDMA { os << (const base& )rs; //type casting //hasDMA parameter to base argument os << "Style: " <<rs.style << endl; return os; } CPS235:Polymorphism38

Computer Science Department Recommended Reading Bruce Eckel’s “Thinking in C++” available online at CPS235:Polymorphism39

Computer Science Department How C++ implements virtual binding CPS235:Polymorphism40

Computer Science Department How C++ implements virtual binding CPS235:Polymorphism41

Computer Science Department Cost of Polymorphism VTABLE for every polymorphic class VPTR embedded in every polymorphic object Indirect function access CPS235:Polymorphism42

Computer Science Department Another Example class Base { public: virtual void function1() {}; virtual void function2() {}; }; class D1: public Base { public: void function1() {}; }; class D2: public Base { public: void function2() {}; }; CPS235:Polymorphism43

Computer Science Department CPS235:Polymorphism44