Polymorphism From now on we will use g++!. Example (revisited) Goal: Graphics package Handle drawing of different shapes Maintain list of shapes.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
Chapter 1 OO using C++. Abstract Data Types Before we begin we should know how to accomplish the goal of the program We should know all the input and.
. Virtual Classes & Polymorphism. Example (revisited) u We want to implement a graphics system u We plan to have lists of shape. Each shape should be.
Plab 2003 Lecture 41 C++ - Classes. Plab 2003 Lecture 42 Motivating Example Goal: Graphics package Handle drawing of different shapes Maintain list of.
. Copying, casting, and more. Example: MyString u Lets put our knowledge of C++ classes to use u Define a class to represent a string u Replace all the.
OOP Spring 2007 – Recitation 71 Object Oriented Programming Spring 2006 Recitation 8.
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.
Inheritance and Polymorphism CS351 – Programming Paradigms.
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.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
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 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
1 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
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.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
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.
Inheritance. Recall the plant that we defined earlier… class Plant { public: Plant( double theHeight ) : hasLeaves( true ), height (theHeight) { } Plant(
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
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.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 10 Inheritance and Polymorphism
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Programming in Java CSCI-2220 Object Oriented Programming.
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.
CSCI-383 Object-Oriented Programming & Design Lecture 18.
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
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.
Overview of C++ Polymorphism
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Object Oriented Programming Elhanan Borenstein Lecture #7.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
ENEE150 – 0102 ANDREW GOFFIN Abstract Data Types.
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.
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.
Modern Programming Tools And Techniques-I
CMSC 202 Polymorphism.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Polymorphism &Virtual Functions
Object-Oriented Programming
Polymorphism.
Polymorphism & Virtual Functions
Polymorphism Lec
Classes in C++ C++ originally called "C with classes":
Virtual Functions Department of CSE, BUET Chapter 10.
Polymorphism CT1513.
Programming II Polymorphism A.AlOsaimi.
CISC/CMPE320 - Prof. McLeod
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
CISC/CMPE320 - Prof. McLeod
Overview of C++ Polymorphism
Chapter 14 Abstract Classes and Interfaces
C++ Polymorphism Reference and pointer implicit type casting
Lecture 6: Polymorphism
Computer Science II for Majors
Presentation transcript:

Polymorphism From now on we will use g++!

Example (revisited) Goal: Graphics package Handle drawing of different shapes Maintain list of shapes

Solution #1 class Shape { public: enum Type { e_square, e_circle, e_triangle }; Shape( Type t, Point center, double width, double height); void draw(); double area(); … private: Type m_type; Point m_center; … };

Solution #1 This solution gives a nice “wrapping” to the solution we consider in C. (switch command) Pros: Simple, direct Cons: Adding new shapes requires changing all procedures that deal with shape. Require fat interface in order to support all kinds of shapes. No type checking. Unsafe!

Solution #2 – different classes class Square { public: void draw(); double area(); … }; class Circle { public: void draw(); double area(); … };

Solution #2 – Discussion Each shape has its own implementation We can easily add new shapes However, Shapes are different types One cannot view them as part of the same class

Solution #3 - Inheritance class Shape { public: void draw(); double area(); … }; class Square: public Shape { public: void draw(); double area(); … }; class Circle: public Shape { public: … void draw(); double area(); … }; …

Solution #3 Now we can write code such as: Shape* myShapes[2]; myShapes[0] = new Circle(); myShapes[1] = new Square(); … What will happen when we call myShapes[0]->draw(); Lets test … see shapes.cpp.shapes.cpp

What is going on? When we write: Circle circle; circle.draw(); The compiler calls Circle::draw(); When we write: Shape* p = new Circle(); p->draw(); The compiler calls Shape::draw() Why? *p has type Shape

Class Hierarchy class Base { public: … void foo(); void bar(); … }; class Derived: public Base{ public: … void bar(); … }; Derived obj; obj.foo(); Calls Base::foo() Derived does not implement this method obj.bar(); Calls Derived::bar() Two implementations, the more specific is used

Inheritance & Overloading Derived inherits the method foo () from Base. –The inherited class is using methods of the base class Derived overloads the implementation of bar (). –This mechanism allows an inherited class to specialize the implementation.

Static resolution How does the compiler determine which method to call? Static Resolution: Based on the type of the variable. –Not the type of the object! The compiler finds the most specific implementation of the method, and calls it.

Static resolution Example Circle* circle = new Circle(1,1,2); Square* square = new Square(2,2,1); Shape* myShapes[2]; myShapes[0] = circle; myShapes[1] = square; circle->draw(); // Calls Circle::draw() square->draw(); // Calls Square::draw() myShapes[0]->draw(); // Calls Shape::draw() myShapes[1]->draw(); // Calls Shape::draw()

Dynamic Resolution This is clearly not what we want to do in this example. A more desirable here solution, Dynamic resolution (Polymorphism): Based on the type of the object. Determined at run time. [Java Like!]

Dynamic Resolution Cont The virtual keyword states that the method can be overloaded in a dynamic manner. class Base { public: … virtual void bar(); … } class Derived: public Base { public: … virtual void bar(); … }

Solution #4: dynamic resolution Returning to the shapes example, using virtual methods gives the desired result See Shapes- virtual.cppvirtual.cpp

Virtual Methods Class Base defines a virtual method foo() The resolution of foo() is dynamic in all subclasses of Base. –If the subclass Derived overloads foo(), then Derived::foo() is called –If not, Base::foo() is called [See nested.cpp]nested.cpp

Underneath the Hood: Inheritance class Base { … private: double m_x; int m_a; }; class Derived : public Base { … private: double m_z; }; class Base a; class Derived b; m_x m_a m_z m_x m_a a: b: Base

Pointing to an Inherited Class class Derived b; class Base* p = &b; When using *p, we treat b as though it was a Base object The compiler cannot know if *p is from a derived class or not. m_x m_a m_z b: p:

Implementation of Virtual Methods Possible approach: If foo() is a virtual method, then each object has a pointer to the implementation of foo() that it uses Essentially the solution we used in our C implementation Cost: Each virtual method requires a pointer Large number of virtual methods  waste of memory

Implementation of Virtual Methods Alternative solution: Each object has a pointer to an array of function pointer This array points to the appropriate functions Cost: For each class, we store one table Each object contains one field that points to the right table

Example class A { public: virtual void f1(); virtual void f2(); int m_a; }; class B: public A { public: virtual void f1(); virtual void f3(); void f4(); int m_b; }; … A a1, a2; B b; class A { public: virtual void f1(); virtual void f2(); int m_a; }; class B: public A { public: virtual void f1(); virtual void f3(); void f4(); int m_b; }; … A a1, a2; B b; void A::f1 { //... }; void A::f1 { //... }; void A::f2 { //... }; void A::f2 { //... }; void B::f1 { //... }; void B::f1 { //... }; VTBLs A B m_a a1: m_a m_b b: m_a a1: void B::f3 { //... }; void B::f3 { //... }; f1 f2 f3 f1 f2

Virtual - Recap Virtual controls whether to use static or dynamic resolution Once a method is virtual, it must remain so throughout the hierarchy Calling a virtual method is more expensive than standard calls –Two pointers are “chased” to get to the address of the function.

Destructors & Inheritance class Base { public: ~Base(); }; class Derived : public Base { public: ~Derived(); }; Base *p = new Derived; … delete p; Which destructor is called? [see destruct.cpp]destruct.cpp

Virtual Destructor Destructor is like any other method The example uses static resolution, and hence not the intended destructor is called To fix that, we need to declare virtual destructor at the base class! See destruct-virt.cppdestruct-virt.cpp Once you declare virtual destructor, derived class must declare a destructor.

Polymorphism & Inheritance C++ allows to use class hierarchy to implement polymorphic code. Points of care: Choice of virtual methods. –Run time considerations efficiency. Use of virtual destructor for base class!

Shapes & Sizes Revisiting our example, we write class Shape { public: … virtual ~Shape(); // virtual destructor virtual void draw(); // virtual method virtual double area(); // also … }; How do we implement Shape::draw() ?

Inheritance & Abstract Classes In this example, we never want to deal with objects of type Shape –Shape serves the role of an interface All shapes need to be specific shapes that are instances of derived classes of Shape How do we enforce this? Simple mechanism: void Shape::draw() { assert(false); // we should never call this method }

Abstract Classes We can specify that Shape::draw() does not exist class Shape { public: … virtual ~Shape(); // virtual destructor virtual void draw() = 0; // pure virtual virtual double area() = 0; // Also … };

Abstract Classes We cannot create objects of a Pure Virtual class Shape* p; // legal Shape s; // illegal Circle c; // legal p = &c; // legal p = new Shape; // illegal

Virtual Methods - Tips If you have virtual methods in a class, always declare its destructor virtual! Never call virtual methods during construction and destruction! (invalid object state) Use virtual methods Duplicate() and Create() for implementing “virtual constructors”. Use pure abstract classes to define interfaces. Use inheritance with care: Be sure that this is the appropriate solution.