Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.

Slides:



Advertisements
Similar presentations
Constructors: Access Considerations DerivedClass::DerivedClass( int iR, float fVar) : BaseClass(fVar) { m_uiRating = uiR; } Alternatively DerivedClass::DerivedClass(
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
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.
V IRTUAL F UNCTIONS Chapter 10 Department of CSE, BUET 1.
Inheritance, Polymorphism, and Virtual Functions
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.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
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.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
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.
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.
1 Inheritance We are modeling the operation of a transportation company that uses trains and trucks to transfer goods. A suitable class hierarchy for the.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
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.
Chapter 9 Questions 1. What are the difference between constructors and member functions? 2. Design and implement a simple class as you want, with constructors.
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.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Chapter -6 Polymorphism
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.
Polymorphism Lecture - 9.
Inheritance - 3. Virtual Functions Functions defined as virtual are ones that the base expects its derived classes may redefine. Functions defined as.
Computer Science Department Inheritance & Polymorphism.
C++ How to Program, 7/e. © by Pearson Education, Inc. All Rights Reserved.2.
CS1201: Programming Language 2 Classes and objects Inheritance Nouf Aljaffan Edited by : Nouf Almunyif.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
CS 3370 – C++ Object-oriented Programming
7. Inheritance and Polymorphism
Polymorphism &Virtual Functions
Class A { public : Int x; A()
Object-Oriented Programming
Inheritance, Polymorphism, and Virtual Functions
Polymorphism.
CS212: Object Oriented Analysis and Design
Polymorphism & Virtual Functions
Polymorphism Lec
Learning Objectives Inheritance Virtual Function.
Virtual Functions Department of CSE, BUET Chapter 10.
Inheritance, Polymorphism, and Virtual Functions
Polymorphism Polymorphism
Programming II Polymorphism A.AlOsaimi.
Pointers Dr. Bhargavi Goswami Department of Computer Science
Virtual Functions Polymorphism is supported by C++ both at compile time and at run time. Compile-time polymorphism is achieved by overloading functions.
Overview of C++ Polymorphism
VIRTUAL FUNCTIONS RITIKA SHARMA.
Inheriting Multiple Base Classes
C++ Polymorphism Reference and pointer implicit type casting
Lecture 6: Polymorphism
Computer Science II for Majors
Presentation transcript:

Polymorphism & Virtual Functions 1

Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to virtual functions  Virtual destructors  More about virtual functions  Final comments  Applying polymorphism

Polymorphism in C++ 3  2 types  Compile time polymorphism  Uses static or early binding  Example: Function and operator overloading  Run time polymorphism  Uses dynamic or early binding  Example: Virtual functions

Pointers to Derived Classes 4 C++ allows base class pointers to point to derived class objects. Lets have – class Base_Class{ … }; class Derived_Class: public Base_Class{ … }; Then we can write – Base_Class *p1; // pointer to object of type Base_Class Derived_Class derived_obj; // object of type Derived_Class Both statement are valid: p1 = &derived_obj; Base_Class *p2 = new Derived_Class;

Pointers to Derived Classes (contd.) 5  Using a base class pointer (pointing to a derived class object) we can access only those members of the derived object that were inherited from the base.  This is because the base pointer has knowledge only of the base class.  It knows nothing about the members added by the derived class.

Pointers to Derived Classes (contd.) 6 class base { public: void show() { cout << “base\n”; } }; class derived : public base { public: void show() { cout << “derived\n”; } }; void main() { base b1; b1.show(); // base derived d1; d1.show(); // derived base *pb = &b1; pb->show(); // base pb = &d1; pb->show(); // base }  All the function calls here are statically bound

Pointers to Derived Classes (contd.) 7  While it is permissible for a base class pointer to point to a derived object, the reverse is not true. base b1; derived *pd = &b1; // compiler error  We can perform a downcast with the help of type-casting, but should use it with caution.

Pointers to Derived Classes (contd.) 8  Let’s have: class base { … }; class derived : public base { … }; class xyz { … }; // having no relation with “base” or “derived”  Then if we write – base b_obj, *pbase; derived d_obj; pbase = &d_obj; // OK derived *pderived = pbase; // compiler error derived *pderived = (derived *)pbase; // ok, valid down casting xyz obj; pderived = (derived *)&obj; //invalid casting, no compiler error, but may cause run-time error pderived = (derived *)&b_obj; //invalid casting, no compiler error, but may cause run-time error

Pointers to Derived Classes (contd.) 9 In fact using type-casting, we can use pointer of any class to point to an object of any other class. The compiler will not complain. During run-time, the address assignment will also succeed. But if we use the pointer to access any member, then it may cause run-time error.

Pointers to Derived Classes (contd.) 10  Pointer arithmetic is relative to the data type the pointer is declared as pointing to.  If we point a base pointer to a derived object and then increment the pointer, it will not be pointing to the next derived object.  It will be pointing to (what it thinks is) the next base object !!!  Be careful about this.

Important Point on Inheritance 11  In C++, only public inheritance supports the perfect IS-A relationship.  In case of private and protected inheritance, we cannot treat a derived class object in the same way as a base class object  Public members of the base class becomes private or protected in the derived class and hence cannot be accessed directly by others using derived class objects  If we use private or protected inheritance, we cannot assign the address of a derived class object to a base class pointer directly.  We can use type-casting, but it makes the program logic and structure complicated.

Introduction to Virtual Functions 12  A virtual function is a member function that is declared within a base class and redefined (called overriding) by a derived class.  It implements the “one interface, multiple methods” philosophy that underlies polymorphism.  The keyword virtual is used to designate a member function as virtual.  Supports run-time polymorphism with the help of base class pointers.

Introduction to Virtual Functions (contd.) 13  While redefining a virtual function in a derived class, the function signature must match the original function present in the base class.  So, we call it overriding, not overloading.  When a virtual function is redefined by a derived class, the keyword virtual is not needed (but can be specified if the programmer wants).  The “virtual”-ity of the member function continues along the inheritance chain.  A class that contains a virtual function is referred to as a polymorphic class.

Introduction to Virtual Functions (contd.) 14  For the polymorphic approach to work, several conditions must be met.  First, all the different derived classes must be descended from a single base class  Second, the overridden function must be declared to be virtual in the base class

Introduction to Virtual Functions (contd.) 15 class base { public: virtual void show() { cout << “base\n”; } }; class derived : public base { public: void show() { cout << “derived\n”; } }; void main() { base b1; b1.show(); // base(s.b.) derived d1; d1.show();// derived(s.b.) base *pb = &b1; pb->show();//base(d.b.) pb = &d1; pb->show();//derived (d.b.) } Here, s.b. = static binding d.b. = dynamic binding

Introduction to Virtual Functions (contd.) 16 class base { public: virtual void show() { cout << “base\n”;} }; class d1 : public base { public: void show() {cout << “derived-1\n”;} }; class d2 : public base { public: void show() {cout << “derived-2\n”; } }; void main() { base *pb; d1 od1; d2 od2; int n; cin >> n; if (n > 2) pb = &od1; else pb = &od2; pb->show(); // guess what ?? } Run-time polymorphism

Virtual Destructors 17  Constructors cannot be virtual, but destructors can be virtual.  It ensures that the derived class destructor is called when a base class pointer is used while deleting a dynamically created derived class object.

Virtual Destructors (contd.) 18 class base { public: ~base() { cout << “destructing base\n”; } }; class derived : public base { public: ~derived() { cout << “destructing derived\n”; } }; void main() { base *p = new derived; delete p; }  Output:  destructing base Using non-virtual destructor

Virtual Destructors (contd.) 19 class base { public: virtual ~base() { cout << “destructing base\n”; } }; class derived : public base { public: ~derived() { cout << “destructing derived\n”; } }; void main() { base *p = new derived; delete p; }  Output:  destructing derived  destructing base Using virtual destructor

Virtual functions are inherited 20 Once function is declared as virtual, it stays virtual no matter how many layers of derived classes it may pass through. //derived from derived, not base class derived2 : public derived{ public: //show() not defined. }; void main() { base b1; derived d1;derived2 d2; base *pb = &b1; pb->show(); // base - (d.b.) pb = &d1; pb->show(); // derived (d.b.) pb = &d2; pb->show(); // derived (d.b.) }

Simple App of virtual function 21 Class figure{ protected: double x,y; public: void set_dim(double I, double J ){ x = I; y = J; } Virtual void show_area(){ Cout <<“No area computation defined”; Cout<<“for this class”;} }; Class triangle: public figure{ Public: Void show_area(){cout<< x* 0.5 * y;} }; Class circle: public figure { public: void show_area(){ cout << x *x;}}; int main() { Figure *p; Triangle t; Circle c; P= &t; P-> set_dim(10.0,5.0); P-> show_area(); p= &c; P-> set_dim(10.0, 0); P-> show_area(); return 0; }

More About Virtual Functions 22 Helps to guarantee that a derived class will provide its own redefinition. If we want to omit the body of a virtual function in a base class, we can use pure virtual functions. virtual ret-type func-name(param-list) = 0; Pure virtual function is a virtual function that has no definition in its base class.

Pure function 23 class figure{ protected: double x,y; public: void set_dim(double I, double j=0){ x=I; y= j; } virtual void show_area()=0 ;// pure function }; It makes a class an abstract class. We cannot create any objects of such classes. It forces derived classes to override it own implementation. Otherwise become abstract too and the complier will report an error.

Simple App of virtual function 24 class figure{ protected: double x,y; public: void set_dim(double I, double j=0){ x=I; Y= j; } virtual void show_area()=0 ;// pure function }; class triangle: public figure{ public: void show_area(){cout<< x* 0.5 * y;}}; class circle: public figure{ public: // no definiton of show_area() will case error }; int main(){ Figure *p; Triangle t; Circle c; // illegal – can’t create P= &t; P-> set_dim(10.0,5.0); P-> show_area(); p= &c; P-> set_dim(10.0); P-> show_area(); return 0; }

Abstract class 25  If a class has at least one pure virtual function, then that class is said to be abstract.  An abstract class has one important feature: there are can be no object of the class.  Instead, abstract class must be used only as a base that other classes will inherit.  Even if the class is abstract, you still can use it to declare pointers, which are needed to support run time polymorphism.

Final Comments 26  Run-time polymorphism is not automatically activated in C++.  We have to use virtual functions and base class pointers to enforce and activate run-time polymorphism in C++.

Applying Polymorphism 27  Early binding  Normal functions, overloaded functions  Nonvirtual member and friend functions  Resolved at compile time  Very efficient  But lacks flexibility  Late binding  Virtual functions accessed via a base class pointer  Resolved at run-time  Quite flexible during run-time  But has run-time overhead; slows down program execution