CSC/ECE 517 Fall 2010/ch5 5c IC: Difference between revisions
m (→Introduction) |
m (→Example in C++) |
||
Line 35: | Line 35: | ||
virtual int method1(); | virtual int method1(); | ||
virtual double method3(); | virtual double method3(); | ||
} | |||
</pre> | |||
The next section of code shows a basic implementation of these methods within these two classes. | |||
<pre> | |||
class A | |||
{ | |||
virtual int method1() | |||
{ | |||
cout << "method1 in class A" << endl; | |||
} | |||
virtual int method2() | |||
{ | |||
cout << "method2 in class A" << endl; | |||
} | |||
}; | |||
class B : public A | |||
{ | |||
virtual int method1() | |||
{ | |||
cout << "method1 in class B" << endl; | |||
} | |||
virtual int method3() | |||
{ | |||
cout << "method3 in class B" << endl; | |||
} | |||
} | } | ||
</pre> | </pre> |
Revision as of 23:49, 1 November 2010
Introduction
Dynamic dispatch is an object-oriented programming concept that refers to the mapping of a method to an object's dynamic runtime type. It is common in many object-oriented languages. Languages such as Java and C++ use single dispatch, while only a few, such as CLOS, use multiple dispatch. Both types of dispatch will be discussed later.
Advantages
- Flexibility
- Extensibility
- Reduces the effort required to change implementation [4]
Disadvantages
- Lookup overhead
- Counter to safety and increased compile-time knowledge
- Obstacle to optimization
- Hinders compiler in determining exact type of objects
Example in C++
Below are two example classes in C++. Class A contains one private attribute and two public virtual methods, method1 and method2. Class B inherits from A, contains one private attribute and two public methods, method1 (which overrides the method defined in class A) and method3.
class A { int aMember1; public: virtual int method1(); virtual void method2(); }; class B : public A { int bMember1; public: virtual int method1(); virtual double method3(); }
The next section of code shows a basic implementation of these methods within these two classes.
class A { virtual int method1() { cout << "method1 in class A" << endl; } virtual int method2() { cout << "method2 in class A" << endl; } }; class B : public A { virtual int method1() { cout << "method1 in class B" << endl; } virtual int method3() { cout << "method3 in class B" << endl; } }
Single vs Multiple Dispatch
Dynamic dispatch comes in 2 types: single and multiple dispatch.
Memory Issues
References
[1] “Dynamic Dispatch in Object-Oriented Languages”, 2004.
[2] M. Muller, “Message Dispatch in Dynamically-Typed Object-Oriented Languages”, Master’s Thesis, University of New Mexico, 1995.
[3] http://en.wikipedia.org/wiki/Dynamic_dispatch
[4] D. Schmidt, "Dynamic Binding C++", http://www.cs.wustl.edu/~schmidt/PDF/C++-dynamic-binding4.pdf, 2006.