1 ָ נן oop Dynamic Binding uBinding uBinding time uMotivation uDynamic Binding uHigh Level Methods.

Slides:



Advertisements
Similar presentations
Understand and appreciate Object Oriented Programming (OOP) Objects are self-contained modules or subroutines that contain data as well as the functions.
Advertisements

Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
Plab 2003 Lecture 41 C++ - Classes. Plab 2003 Lecture 42 Motivating Example Goal: Graphics package Handle drawing of different shapes Maintain list of.
HST 952 Computing for Biomedical Scientists Lecture 2.
Stéphane Ducasse6.1 Essential Concepts Why OO? What is OO? What are the benefits? What are the KEY concepts? Basis for all the lectures.
OOP Spring 2007 – Recitation 71 Object Oriented Programming Spring 2006 Recitation 8.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
1 Introduction to C++ Programming Concept Basic C++ C++ Extension from C.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation - a language mechanism for restricting access to some.
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,
Lecture 6: Polymorphism - The fourth pillar of OOP - 1.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
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 Virtual Functions and Polymorphism Chapter What You Will Learn What is polymorphism? How to declare and use virtual functions for abstract classes.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Introduction to Object-oriented programming and software development Lecture 1.
Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
CISC6795: Spring Object-Oriented Programming: Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
OOP and Dynamic Method Binding Chapter 9. Object Oriented Programming Skipping most of this chapter Focus on 9.4, Dynamic method binding – Polymorphism.
Objective-C1 CS151 Presentation: Objective C Kai Tai Pang William Sze.
CSCI 383 Object-Oriented Programming & Design Lecture 17 Martin van Bommel.
CSSE501 Object-Oriented Development. Chapter 11: Static and Dynamic Behavior  In this chapter we will examine the differences between static and dynamic.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
SNPL1 Woochang Lim What (Variable) + How (Function) = Object Objects are the physical and conceptual things we find in the universe around us. Object-Oriented.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
Slide 20.1 Copyright © 2004 by The McGraw-Hill Companies, Inc. All rights reserved. An Introduction to Object-Oriented Systems Analysis and Design with.
CSC241 Object-Oriented Programming (OOP) Lecture No. 16.
Object Oriented Software Development
1 Lecture 6: Polymorphism - The fourth pillar of OOP -
Dynamic Binding Object-Oriented Programming Spring
Object-Oriented Programming Chapter Chapter
Object Oriented Programming
S.Ducasse Stéphane Ducasse 1 Essential OO Concepts Stéphane Ducasse.
ISBN Object-Oriented Programming Chapter Chapter
Introduction to Object-Oriented Programming Lesson 2.
Principles of programming languages 10: Object oriented languages Isao Sasano Department of Information Science and Engineering.
Dynamic Binding Implementation Object-Oriented Programming Spring
CSCI-383 Object-Oriented Programming & Design Lecture 24.
Lecture 2: Review of Object Orientation. © Lethbridge/La ganière 2005 Chapter 2: Review of Object Orientation What is Object Orientation? Procedural.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 20 - Virtual Functions Outline 20.1Introduction 20.2Type Fields and switch Statements 20.3Virtual.
Lecture 2 Intro. To Software Engineering and Object-Oriented Programming (2/2)
CSCI-383 Object-Oriented Programming & Design Lecture 17.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Chapter 12: Support for Object- Oriented Programming Lecture # 18.
CSCI 383 Object-Oriented Programming & Design Lecture 22 Martin van Bommel.
CMSC 202 Polymorphism.
OOP What is problem? Solution? OOP
Inheritance and Run time Polymorphism
Classes in C++ C++ originally called "C with classes":
Object Oriented Programming
Programming with ANSI C ++
Object-Oriented Programming (OOP) Lecture No. 28
Classes in C++ C++ originally called "C with classes":
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
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.
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
VIRTUAL FUNCTIONS RITIKA SHARMA.
C++ Object Oriented 1.
Lecture 6: Polymorphism
Computer Science II for Majors
Presentation transcript:

1 ָ נן oop Dynamic Binding uBinding uBinding time uMotivation uDynamic Binding uHigh Level Methods

2 ָ נן oop Binding Time uBinding: linking between messages and methods uThe same entity may refer to objects of different classes, each of which has a different implementation of the same method More generally, binding time is the time when an attribute of some portion of a program, or the meaning of a particular construct is determined Compile Time Link Time Execution Time: Program Init Procedure/function begin Statement Execution uStatic Binding (AKA Early Binding): the compiler uses the type of variables to do the binding at a compile (link) time uDynamic Binding (AKA Late Binding): the decision is made at run time based on the type of the actual values Inclusion Polymorphism + Overriding = Binding Question

3 ָ נן oop Main Binding Techniques Early (static) binding, is the binding of functions in a program at compile time. The programmer knows the type of data for each function called. For example: AddRealNums(x, y) x, y - of type real. Late (dynamic) binding of the message selector to the appropriate method at run time. The programmer doesn't know the specific method that will be used. For example: AddNumbers(x, y) x, y - are number objects.

4 ָ נן oop Static vs. Dynamic Types uConsider the call: Manager M; M.raise_salary(10); uWhat is the type of this in the called method? lStatic Type: Employee * What can be determined in compile time lDynamic Type: Manager * Actual type, as determined in run time No simple way for the programmer to examine the dynamic type uSuppose that raise_salary calls print, then, which version of print will be called? lBased on the static type? or, lBased on the dynamic type? Employee raise_salary print + Employee raise_salary print + Manager print ++ Manager print ++

5 ָ נן oop Static vs. Dynamic Binding uStatic Binding: binding based on static type. lMore efficient lLess flexible lStatic type checking leads to safer programs uDynamic Binding: binding based on dynamic type. lLess efficient lMore flexible lMay need dynamic type checking! uAs it turns out, dynamic binding is the only reasonable choice: lWhy? lIf static typing is so good, why “spoil” it with dynamic binding?

6 ָ נן oop Motivation I: Containers #define SIZEOF(a) (sizeof(a)/sizeof(*a))... Manager Alice, Bob; Engineer Chuck, Dan, Eve; SalesPerson Faith, Gil, Hugh; Employee Ira, Jim, Kelly;.... Employee *delegation[] = { &Bob, &Dan, &Faith, &Kelly};... for (int i = 0; i < SIZEOF(delegation); i++) delegation[i]->print(cout); Employee print + SalesPerson print ++ Manager print ++ Engineer print ++ Which print should be called here?

7 ָ נן oop Another Container Example uA display list in a graphic application. uList elements: lObjects of subclasses of class Shape: Points, lines, triangles, rectangles, circles, etc. uWe want the list to contain elements of type Shape, but each should be capable of preserving its own special properties. uIf we loop over the list and send each element in it a draw message, the element should respond according to its “dynamic type”.

8 ָ נן oop class Shape { Point location; public:... void move(Point delta) { hide(); location += delta; draw(); }... }; class Rectangle: public Shape { public: void hide(void) const {... } void draw(void) const {... } }; class Shape { Point location; public:... void move(Point delta) { hide(); location += delta; draw(); }... }; class Rectangle: public Shape { public: void hide(void) const {... } void draw(void) const {... } }; Which hide should be called here? Which draw should be called here? Motivation II: High Level Methods Shape location draw* hide* move + (delta) Some Shape draw + hide + uHigh Level Methods: methods which are coded using only the public interface of a class. uFacilitate code reuse in inheritance.

9 ָ נן oop Motivation III: External Functions void duplicate(const Shape *base) { enum {Dx = 12, Dy = 30}; Shape *clone = base->clone(); clone->move(Dx,Dy); clone->draw(); } void duplicate(const Shape *base) { enum {Dx = 12, Dy = 30}; Shape *clone = base->clone(); clone->move(Dx,Dy); clone->draw(); } Shape clone+, draw+ Star clone++, draw++ Which version of draw() and clone() should be called here?

10 ָ נן oop Dynamic Binding is the Answer! uThe rule: A called method should be selected based on the actual type of the object it is sent to. lMeaningful only for reference semantics. Value semantics: dynamic type == static type. lThis is why this is a pointer to the object, rather than the object itself. In a “better C++” this would be a reference to an object. Archaic C++ code used the idiom this = 0. uAll methods in Smalltalk, Eiffel and all other “decent” object-oriented programming languages are dynamically bound.

11 ָ נן oop Dynamic Binding in C? struct Shape { int x, y;... /* Other common fields */ Shape_type type; union { struct Rectangle {... } r; struct Circle {... } c; struct Line {... } l;.../* Other shape kinds */ } data; }; struct Shape { int x, y;... /* Other common fields */ Shape_type type; union { struct Rectangle {... } r; struct Circle {... } c; struct Line {... } l;.../* Other shape kinds */ } data; }; enum Shape_type { rectangle, circle, line,... }; void rotate(Shape *p) { switch (p->type) { case rectangle:... case circle:... case line: } } void rotate(Shape *p) { switch (p->type) { case rectangle:... case circle:... case line: } } void draw(Shape *p) { switch (p->type) { case rectangle:... case circle:... case line: } } void draw(Shape *p) { switch (p->type) { case rectangle:... case circle:... case line: } } Strong Coupling pointers to functions can be used instead.

12 ָ נן oop Disadvantages of the C Solutions uImplicit assumption: consistency between value of the type tag and usage of the union field data. lProgrammer’s responsibility: no compiler aid or checking uDispersed coding: the code for different operations on the same shape is spread all over the program. lDifficult to understand uInsusceptibility to change: whenever a new kind of shape is introduced, the following must be changed: lDefinition of Shape_type lDefinition of Shape lFunction rotate lFunction draw lAll other functions Some OO programming languages do not include a switch like statement, just because of the above bad usage of switch !

13 ָ נן oop class Circle: public Shape { public: virtual void draw(void) {... } virtual void hide(void) {... } //... }; The Shapes Example in C++ class Shape { public: virtual void draw(void); virtual void hide(void); virtual void rotate(int deg);... protected: int x, y;... /* Other common fields */ }; class Shape { public: virtual void draw(void); virtual void hide(void); virtual void rotate(int deg);... protected: int x, y;... /* Other common fields */ }; class Line: public Shape { public: virtual void draw(void) {... } virtual void hide(void) {... } //... }; class Rectangle: public Shape { public: virtual void draw(void) {... } virtual void hide(void) {... } //... }; The specialized code is associated with the type, not with each function. OOP promotes the shift of focus from operations to operands The type tag is hidden, and maintained by the compiler

14 ָ נן oop Downcasting vs. Dynamic Binding void draw(Shape *p) { if (Circle *q = dynamic_cast p) { // Draw circle... } else if (Line *q = dynamic_cast p) { // Draw line... } else if (Rectangle *q = dynamic_cast p) { // Draw rectangle... }... } void draw(Shape *p) { if (Circle *q = dynamic_cast p) { // Draw circle... } else if (Line *q = dynamic_cast p) { // Draw line... } else if (Rectangle *q = dynamic_cast p) { // Draw rectangle... }... } RTTI considered harmful: lOrder of classes in the if chains is significant lModule must change whenever new class is added to the hierarchy

15 ָ נן oop Dynamic Binding and the Container Problem uGiven is a set of employees as in Employee *department[100]; uThen, how can we determine if a department[3] is a manager or not? uDynamic Binding Answer: lThe question is wrong!!! lThere is never a need to determine the dynamic type of an object. lDifferences between objects: Different state lDifferences between classes: Different implementation uUsage of RTTI in all but very special cases indicates a misunderstanding of the power of dynamic binding.

16 ָ נן oop High Level Methods Dynamic binding makes methods truly polymorphic. The same code will do different things for different objects: void Shape::move(Point delta) { hide(); location += delta; draw(); } void Shape::move(Point delta) { hide(); location += delta; draw(); } Internal (in-class) dynamic binding uLow level methods: implemented only using data members u code not affected by overriding uHigh level methods: may use also other methods u partially polymorphic code uOuter level methods: methods implemented solely with (externally accessible) methods u fully polymorphic code

17 ָ נן oop Dynamic Binding and Static Typing uStatic typing: guarantee that a method exists lA variable of type T can contain only objects of type T, or of type T', where T' is derived from T. lA message to an object is legal only if its static type recognizes it. uDynamic binding: make sure that the right method is selected. lThe method invoked for an object depends on its dynamic type. uStatic typing + Dynamic binding: the right combination of safety and power lExamples: Eiffel, C++, Java, Object-Pascal, Turbo-Pascal, etc.

18 ָ נן oop C++ Example struct Base { virtual void f(void) {... } void g(void) {...} }; struct Derived: public Base { virtual void f(void) {...} // Override f() of Base void g(void) {...} // Override g() of Base void h(void) {...} } y; Base *px = &y; px->f(); // The right method px->g(); // The wrong method px->h(); // Compile time error! No guarantee that the method exists struct Base { virtual void f(void) {... } void g(void) {...} }; struct Derived: public Base { virtual void f(void) {...} // Override f() of Base void g(void) {...} // Override g() of Base void h(void) {...} } y; Base *px = &y; px->f(); // The right method px->g(); // The wrong method px->h(); // Compile time error! No guarantee that the method exists

19 ָ נן oop Comparison of Binding Techniques uDynamic binding is more flexible. Static is more efficient. lStatic types are more efficient. lCalling static methods is more efficient. uStatic method binding may give better error detection, just as static typing gives better error detection. uUsage: lStatic binding: homogenous set of objects that are similar to an existing class; inheritance simply makes the new set of objects easier to implement. lDynamic binding: heterogeneous mix of objects that share operations that are conceptually the same, but may have different implementations.