. 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.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Lecture 10: Part 1: OO Issues CS 540 George Mason University.
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.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Polymorphism From now on we will use g++!. Example (revisited) Goal: Graphics package Handle drawing of different shapes Maintain list of shapes.
Plab 2003 Lecture 41 C++ - Classes. Plab 2003 Lecture 42 Motivating Example Goal: Graphics package Handle drawing of different shapes Maintain list of.
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
Plab 2003 Exercise 4. Pointers to pointers. Plab 2003 Exercise 4 2 Pointers to pointers (1)int i=3 (2)int j=4; (3)int k=5; 3 i: 4 j: 5 k: ip1: ip2: (4)int.
. 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.
. Memory Management. Memory Organization u During run time, variables can be stored in one of three “pools”  Stack  Static heap  Dynamic heap.
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.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
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.
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.
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.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
The Procedure Abstraction, Part VI: Inheritance in OOLs Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 10 Inheritance and Polymorphism
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
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.
Overview of C++ Polymorphism
OBJECT ORIENTED PROGRAMMING. Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
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.
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.
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
Web Design & Development Lecture 9
CMSC 202 Polymorphism.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Polymorphism &Virtual Functions
Object-Oriented Programming
Polymorphism & Virtual Functions
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 14: 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.
Overview of C++ Polymorphism
Chapter 14 Abstract Classes and Interfaces
Computer Science II for Majors
Presentation transcript:

. 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 able to draw it self, compute its size, etc.

Solution #1 class Shape { public: enum Type { Square, Circle, Triangle }; Shape( Type t, Point Center, double width, double height); void Draw(); double Area(); … private: Type m_type; Point m_center; … };

Solution #1 u This solution gives a nice “wrapping” to the solution we consider in C u It does not solve the problems of that solution  Lack of extendibility

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

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

Solution #3 - hierarchy 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.

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() u Two implementations, the more specific is used

Inheritance & Overloading  Derived inherits the method foo () from Base  The inherited class to use methods of the base class  Derived overloads the implementation of bar ()  This mechanism allows an inherited class to specialize the implementation

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

Static resolution in our 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 u This clearly not what we want to in this example u More desirable here is Dynamic resolution: u Based on the type of the object u Determined at run time [Java Like]

Dynamic Resolution in C++ u 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 u Returning to the shapes example, using virtual methods gives the desired result u See Shapes-virtual.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]

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; u 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 u Essentially the solution we used in our C implementation Cost: u Each virtual method requires a pointer Large number of virtual methods  waste of memory

Implementation of Virtual Methods Alternative solution: u Each object has a pointer to an array of function pointer u This array points to the appropriate functions Cost: u For each class, we store one table u 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 u Virtual controls whether to use static or dynamic resolution u Once a method is virtual, it must remain so throughout the hierarchy u 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]

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

Polymorphism & Inheritance u C++ allows to use class hierarchy to implement polymorphic code Points of care: u Choice of virtual methods  Run time considerations u 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 & Interfaces  In this example, we never want to deal with objects of type Shape  Shape serves the role of an interace  All shapes need to be specific shapes that are instances of derived classes of Shape u How do we enforce this? Simple mechanism: void Shape::Draw() { assert(false); // we should never call this method }

Pure Virtual 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 … };

Pure Virtual u 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 u If you have virtual methods in a class, always declare its destructor virtual u Never call virtual methods during construction and destruction u Use virtual methods Duplicate() and Create() for implementing “virtual constructors” u Use pure virtual classes to define interfaces u Use inheritance with care: Be sure that this is the appropriate solution

Post Quiz issues…. Things to brush up on: u Preprocessor vs. Compiler u #define and how it works u Compiler vs. Linkage

Example void main() { (1) int *y = (int*)malloc( 3*sizeof(int) ); (2) int x[] = {1,2,3}; (3) int ** pp = NULL; (4) int *z = y; } A space on the memory heap was allocated in the following lines: a. 1 b. 2 c. 3 d. 4

Another int *ip = (int*)malloc(100*sizeof(int)); (*ip) += 30; free(ip); 1This code will generate a compilation error. 2This code can generate unpredictable run-time behavior. 3No error would occur if we only check if ip equals NULL before calling the "free" function 4The code contains no error.

Something else…. char s[] = {'p','l','a','b'}; What will be returned by calling strcmp(s,"plab")? 1. a negative number a positive number 4. We cannot know for sure

Almost Last Example struct MyStruct { int x[3]; }; void f(MyStruct s) { s.x[0] = 15; s.x[1] = 16; s.x[2] = 17; } int main() { MyStruct s; f(s); printf("%d %d %d\n", s.x[0], s.x[1], s.x[2]); }

Similar but not quite… struct MyStruct { int x[3]; }; void f(MyStruct* s) { s->x[0] = 15; s->x[1] = 16; s->x[2] = 17; } int main() { MyStruct s; f(&s); printf("%d %d %d\n", s.x[0], s.x[1], s.x[2]); }

Final Example typedef void (*myfunc)(int*); void foo(int * x) { x[0] += 2; } void bar( int * x ) { x[1] += 2; } main() { myfunc funcs[2] = { foo, bar }; int arr[] = {3,4,5}; (funcs[0])(arr); (funcs[1])(arr+1); printf("%d %d %d\n",arr[0],arr[1],arr[2]) ; }