1
1
Dynamic Binding
Dynamic Binding
(Section 10.4)
(Section 10.4)
CSCI 431 Programming Languages
CSCI 431 Programming Languages
Fall 2003
Fall 2003
A compilation of material developed by Felix
A compilation of material developed by Felix
Hernandez-Campos and
Hernandez-Campos and Mircea Nicolescu
Mircea Nicolescu
2
2
Fundamental Concepts in OOP
Fundamental Concepts in OOP
• Encapsulation
Encapsulation
– Data Abstraction
Data Abstraction
– Information hiding
Information hiding
– The notion of class and object
The notion of class and object
• Inheritance
Inheritance
– Code reusability
Code reusability
– Is-a vs. has-a relationships
Is-a vs. has-a relationships
• Polymorphism
Polymorphism
– Dynamic method binding
Dynamic method binding
3
3
Inheritance
Inheritance
• Encapsulation improves code reusability
Encapsulation improves code reusability
– Abstract Data Types
Abstract Data Types
– Modules
Modules
– Classes
Classes
• However, it is generally the case that the code a
However, it is generally the case that the code a
programmer wants to reuse is close but not exactly
programmer wants to reuse is close but not exactly
what the programmer needs
what the programmer needs
• Inheritance
Inheritance provides a mechanism to extend or
provides a mechanism to extend or
refine units of encapsulation
refine units of encapsulation
– By adding or
By adding or overriding
overriding methods
methods
– By adding attributes
By adding attributes
4
4
Inheritance
Inheritance
Notation
Notation
Java.awt.Dialog
Java.awt.Dialog
Java.awt.FileDialog
Java.awt.FileDialog
Base Class
Base Class
(or Parent Class
(or Parent Class
or Superclass)
or Superclass)
Derived Class
Derived Class
(or Child Class
(or Child Class
or Subclass)
or Subclass)
Is-a relationship
Is-a relationship
5
5
Dynamic Method Binding
Dynamic Method Binding
• Consequence of inheritance
Consequence of inheritance
– derived class
derived class D
D has all members of its base class
has all members of its base class B
B
– can use an object of class
can use an object of class D
D everywhere an object of class
everywhere an object of class B
B is expected
is expected
» a form of polymorphism
a form of polymorphism
• Example (C++):
Example (C++):
class person { ... };
class person { ... };
class student : public person { ... };
class student : public person { ... };
class professor : public person { ... };
class professor : public person { ... };
student s;
student s;
professor p;
professor p;
...
...
person * x = &s;
person * x = &s;
person * y = &p;
person * y = &p;
// Both
// Both student
student and
and professor
professor objects have all properties of
objects have all properties of
// a
// a person
person object
object
// Both can be used in a
// Both can be used in a person
person context
context
6
6
Dynamic Method Binding
Dynamic Method Binding
• Example (C++):
Example (C++):
class person { ... };
class person { ... };
class student : public person { ... };
class student : public person { ... };
class professor : public person { ... };
class professor : public person { ... };
void person::print_mailing_label () { ... }
void person::print_mailing_label () { ... }
student s;
student s;
professor p;
professor p;
...
...
person * x = &s;
person * x = &s;
person * y = &p;
person * y = &p;
s.print_mailing_label ();
s.print_mailing_label ();
p.print_mailing_label ();
p.print_mailing_label ();
// person::print_mailing_label ()
// person::print_mailing_label ()
// person::print_mailing_label ()
// person::print_mailing_label ()
7
7
Dynamic Method Binding
Dynamic Method Binding
• Example (C++):
Example (C++):
– Suppose that we redefine
Suppose that we redefine print_mailing_label
print_mailing_label in both derived classes
in both derived classes
void student::print_mailing_label () { ... }
void student::print_mailing_label () { ... }
void professor::print_mailing_label () { ... }
void professor::print_mailing_label () { ... }
student s;
student s;
professor p;
professor p;
...
...
person * x = &s;
person * x = &s;
person * y = &p;
person * y = &p;
s.print_mailing_label ();
s.print_mailing_label ();
p.print_mailing_label ();
p.print_mailing_label ();
// student ::print_mailing_label ()
// student ::print_mailing_label ()
// professor ::print_mailing_label ()
// professor ::print_mailing_label ()
– But what about:
But what about:
x->print_mailing_label ();
x->print_mailing_label (); // ??
// ??
y->print_mailing_label ();
y->print_mailing_label (); // ??
// ??
8
8
Dynamic Method Binding
Dynamic Method Binding
– Two alternatives for choosing the
Two alternatives for choosing the
method to call:
method to call:
» according to the types of variables (references)
according to the types of variables (references) x
x and
and y
y –
– static method binding
static method binding
(will call the method of
(will call the method of person
person in both cases)
in both cases)
» according to the types of objects
according to the types of objects s
s and
and p
p to which
to which x
x and
and y
y refer –
refer – dynamic
dynamic
method binding
method binding (will call the methods of
(will call the methods of student
student /
/ professor
professor)
)
– Dynamic method binding – central issue to object-oriented programming
Dynamic method binding – central issue to object-oriented programming
– Example – list of
Example – list of persons
persons that have overdue library books
that have overdue library books
» list may contain both
list may contain both students
students and
and professors
professors
» traverse the list and print a mailing label - call the appropriate subroutine
traverse the list and print a mailing label - call the appropriate subroutine
• Example (C++):
Example (C++): student s;
student s;
professor p;
professor p;
...
...
person * x = &s;
person * x = &s;
person * y = &p;
person * y = &p;
x->print_mailing_label ();
x->print_mailing_label (); // ??
// ??
y->print_mailing_label ();
y->print_mailing_label (); // ??
// ??
9
9
Dynamic Method Binding
Dynamic Method Binding
• Simula, C++, Ada 95
Simula, C++, Ada 95
– static method binding by default
static method binding by default
– run-time overhead
run-time overhead
• Smalltalk, Modula-3
Smalltalk, Modula-3
– dynamic method binding
dynamic method binding
• Java, Eiffel
Java, Eiffel
– dynamic method binding by default
dynamic method binding by default
– individual methods can be labeled
individual methods can be labeled final
final (Java) or
(Java) or frozen
frozen (Eiffel)
(Eiffel)
» cannot be overriden by derived classes
cannot be overriden by derived classes
» use static method binding
use static method binding
• Disadvantage of dynamic method binding
Disadvantage of dynamic method binding
– how do we specify dynamic binding in C++?
how do we specify dynamic binding in C++?
» label individual methods as
label individual methods as virtual
virtual
10
10
Virtual and Non-Virtual Methods
Virtual and Non-Virtual Methods
• C++
C++
class person
class person
{
{
public:
public:
virtual void print_mailing_label ();
virtual void print_mailing_label ();
...
...
}
}
– if
if print_mailing_label
print_mailing_label is overridden in classes
is overridden in classes student
student and
and professor
professor
» at run time, the appropriate one is chosen – dynamic binding
at run time, the appropriate one is chosen – dynamic binding
• Terminology in C++:
Terminology in C++:
– redefine
redefine a method that uses static binding
a method that uses static binding
– override
override a method that uses dynamic binding
a method that uses dynamic binding
11
11
Virtual and Non-Virtual Methods
Virtual and Non-Virtual Methods
• Ada
Ada
– methods take as parameter the object they are applied to
methods take as parameter the object they are applied to
– dynamic binding is associated not with the method but with the parameter
dynamic binding is associated not with the method but with the parameter
– here,
here, r
r needs to be declared as
needs to be declared as person'Class
person'Class →
→ dynamic binding
dynamic binding
12
12
Virtual and Non-Virtual Methods
Virtual and Non-Virtual Methods
• Static method binding is more efficient
Static method binding is more efficient
• When could it be undesirable?
When could it be undesirable?
– May not preserve consistency in the derived class
May not preserve consistency in the derived class
– Example:
Example:
class text_file
class text_file
{
{
char * name;
char * name;
long crt_pos;
long crt_pos;
public:
public:
void seek (long pos);
void seek (long pos); // non-virtual
// non-virtual
...
...
};
};
class read_ahead_text_file : public text_file
class read_ahead_text_file : public text_file
{
{
char * upcoming_chars;
char * upcoming_chars;
public:
public:
void seek (long pos);
void seek (long pos); // redefinition
// redefinition
// also updates the
// also updates the upcoming_chars
upcoming_chars
...
...
};
};
– with static binding:
with static binding:
» text_file::seek
text_file::seek may be called for a
may be called for a read_ahead_text_file
read_ahead_text_file object, if used where
object, if used where
text_file
text_file was expected
was expected
» state of the
state of the read_ahead_text_file
read_ahead_text_file object would become inconsistent
object would become inconsistent
13
13
Abstract Classes
Abstract Classes
• C++
C++ class person
class person
{
{
...
...
public:
public:
virtual void print_mailing_label () = 0;
virtual void print_mailing_label () = 0;
...
...
};
};
– Abstract method
Abstract method – virtual method with no body
– virtual method with no body
» also called
also called pure virtual method
pure virtual method in C++
in C++
– Abstract class
Abstract class – it has at least one abstract method
– it has at least one abstract method
» cannot declare objects of an abstract class, just pointers
cannot declare objects of an abstract class, just pointers
– Purpose of an abstract class:
Purpose of an abstract class:
» serve as base to derive
serve as base to derive concrete classes
concrete classes
» a
a concrete class
concrete class must provide a definition for every abstract method it inherits
must provide a definition for every abstract method it inherits
– Interface
Interface (Java) –
(Java) – class with no other members than abstract methods
class with no other members than abstract methods
14
14
Member Lookup
Member Lookup
• Static method binding:
Static method binding:
– easy to find the method to call, based on the type of the variable
easy to find the method to call, based on the type of the variable
– performed at compile time
performed at compile time
• Dynamic method binding
Dynamic method binding
– appropriate method is identified at run-time
appropriate method is identified at run-time
– objects must contain information to allow for finding the appropriate
objects must contain information to allow for finding the appropriate
method
method
– each object contains a pointer to a
each object contains a pointer to a virtual method table
virtual method table (
(vtable
vtable)
)
– all objects of a given class have the same
all objects of a given class have the same vtable
vtable
15
15
Member Lookup
Member Lookup
– The compiler will generate:
The compiler will generate:
• Implementation of a
Implementation of a vtable
vtable:
:
– Consider the code:
Consider the code:
foo * f;
foo * f;
f->m();
f->m();
– Runtime overhead (compared to static binding) – two instructions
Runtime overhead (compared to static binding) – two instructions
16
16
Member Lookup
Member Lookup
• When defining a derived class:
When defining a derived class:
– Ordering is essential:
Ordering is essential:
» all new members introduced by
all new members introduced by bar
bar must appear at the end:
must appear at the end:
» additional data members (
additional data members (w
w) at the end of the record
) at the end of the record
» additional virtual methods (
additional virtual methods (s
s and
and t
t) at the end of the
) at the end of the vtable
vtable
» virtual methods overridden in
virtual methods overridden in bar
bar (such as
(such as m
m) – appear in
) – appear in bar
bar's
's vtable
vtable at the
at the
same place as in
same place as in foo
foo's
's vtable
vtable
17
17
Member Lookup
Member Lookup
• Allowed operations (same example):
Allowed operations (same example):
class foo { ... };
class foo { ... };
class bar : public foo { ... };
class bar : public foo { ... };
...
...
foo F;
foo F;
bar B;
bar B;
foo * q;
foo * q;
bar * s;
bar * s;
q = &B;
q = &B; //
//
s = &F;
s = &F; //
//
ok; references through
ok; references through q
q will use prefixes of
will use prefixes of B
B's data space and
's data space and vtable
vtable
static semantic error;
static semantic error; F
F lacks the additional data and
lacks the additional data and vtable
vtable entries of a
entries of a bar
bar
18
18
Type Checking
Type Checking
still an error
still an error
ok, but risky – programmer must ensure that
ok, but risky – programmer must ensure that q
q
refers to a
refers to a bar
bar object
object
C++ specific – involves dynamic type check
C++ specific – involves dynamic type check
• C++
C++
class foo { ... };
class foo { ... };
class bar : public foo { ... };
class bar : public foo { ... };
– Type correctness of the code above – checked statically
Type correctness of the code above – checked statically
foo F;
foo F;
bar B;
bar B;
foo * q;
foo * q;
bar * s;
bar * s;
...
...
q = &B;
q = &B;
s = &F;
s = &F;
s = q;
s = q; //
//
– But it can be done:
But it can be done:
s = (bar*) q;
s = (bar*) q; //
//
– Better solution:
Better solution:
s = dynamic_cast<bar*> (q);
s = dynamic_cast<bar*> (q); //
//
19
19
Type Checking
Type Checking
• Java
Java
– allows only the "classic" cast, but with dynamic check
allows only the "classic" cast, but with dynamic check
• Eiffel
Eiffel
class foo ...
class foo ...
class bar inherit foo ...
class bar inherit foo ...
...
...
f : foo;
f : foo;
b : bar;
b : bar;
...
...
f := b;
f := b; -- always ok
-- always ok
b ?= f;
b ?= f; -- reverse assignment, with dynamic check
-- reverse assignment, with dynamic check
– Reverse assignment
Reverse assignment ?=
?= assigns an object reference into a variable only if
assigns an object reference into a variable only if
the type at run-time is acceptable
the type at run-time is acceptable
» b
b gets
gets f
f if
if f
f refers to a
refers to a bar
bar object at run-time
object at run-time
» otherwise
otherwise b
b gets
gets nil
nil
20
20
Type Checking – Implementation
Type Checking – Implementation
• Eiffel, Java, C++
Eiffel, Java, C++
– what is needed to perform dynamic checking?
what is needed to perform dynamic checking?
» run-time
run-time type descriptor
type descriptor included in the object representation
included in the object representation
• Smalltalk
Smalltalk
– variables are untyped references
variables are untyped references
– data members are never public
data members are never public
– any assignment is legal
any assignment is legal
– only method invocation ("send a message") is dynamically checked
only method invocation ("send a message") is dynamically checked
» implementation – dictionary that maps method names to their code
implementation – dictionary that maps method names to their code
» run-time – lookup in dictionary to check if method is supported
run-time – lookup in dictionary to check if method is supported
» if not – dynamic semantic error
if not – dynamic semantic error
– comparison to C++ approach:
comparison to C++ approach:
» more flexible in Smalltalk
more flexible in Smalltalk
» less efficient – increased run-time cost
less efficient – increased run-time cost
» delayed reporting of errors
delayed reporting of errors
21
21
Member Lookup
Member Lookup
• Disadvantages of virtual methods:
Disadvantages of virtual methods:
– run-time cost
run-time cost
– preclude in-line expansion of methods at compile time
preclude in-line expansion of methods at compile time
» performance decrease for small and frequently called methods
performance decrease for small and frequently called methods
• Potential problem with static lookup:
Potential problem with static lookup:
– fragile base class
fragile base class problem (Java):
problem (Java):
» large standard library, evolving over time (adding new features)
large standard library, evolving over time (adding new features)
» user may have old library and run code designed for new library
user may have old library and run code designed for new library
» code may use the new features
code may use the new features
» static lookup
static lookup – invalid memory access
– invalid memory access
» dynamic lookup
dynamic lookup – better, produce error message ("member not found")
– better, produce error message ("member not found")
22
22
Classes as "Closures"
Classes as "Closures"
• Classes – can implement a mechanism similar to
Classes – can implement a mechanism similar to first-class
first-class
subroutines
subroutines
23
23
Classes as "Closures"
Classes as "Closures"
• Advantage of latter version (with classes):
Advantage of latter version (with classes):
– can also add data members to class
can also add data members to class bar
bar (and object
(and object my_obj
my_obj)
)
– function
function f
f can use them
can use them
– similarity between:
similarity between:
» data members of an object with a virtual method,
data members of an object with a virtual method, AND
AND
» referencing environment of a
referencing environment of a closure
closure in a language with nested scopes
in a language with nested scopes
• Application:
Application:
– discrete event simulation
discrete event simulation
– need to have a subroutine
need to have a subroutine schedule_at
schedule_at that:
that:
» takes as parameters a time value and a function
takes as parameters a time value and a function f
f (to be called at that time)
(to be called at that time)
» function
function f
f should have an arbitrary set of parameters
should have an arbitrary set of parameters
– how do we pass such a function
how do we pass such a function f
f (with ANY number of parameters)?
(with ANY number of parameters)?
» pass a "closure" instead – implemented with classes
pass a "closure" instead – implemented with classes
24
24
Classes as "Closures"
Classes as "Closures"
• Example - discrete event simulation:
Example - discrete event simulation:

dynamic binding ppt is important for education perpose

  • 1.
    1 1 Dynamic Binding Dynamic Binding (Section10.4) (Section 10.4) CSCI 431 Programming Languages CSCI 431 Programming Languages Fall 2003 Fall 2003 A compilation of material developed by Felix A compilation of material developed by Felix Hernandez-Campos and Hernandez-Campos and Mircea Nicolescu Mircea Nicolescu
  • 2.
    2 2 Fundamental Concepts inOOP Fundamental Concepts in OOP • Encapsulation Encapsulation – Data Abstraction Data Abstraction – Information hiding Information hiding – The notion of class and object The notion of class and object • Inheritance Inheritance – Code reusability Code reusability – Is-a vs. has-a relationships Is-a vs. has-a relationships • Polymorphism Polymorphism – Dynamic method binding Dynamic method binding
  • 3.
    3 3 Inheritance Inheritance • Encapsulation improvescode reusability Encapsulation improves code reusability – Abstract Data Types Abstract Data Types – Modules Modules – Classes Classes • However, it is generally the case that the code a However, it is generally the case that the code a programmer wants to reuse is close but not exactly programmer wants to reuse is close but not exactly what the programmer needs what the programmer needs • Inheritance Inheritance provides a mechanism to extend or provides a mechanism to extend or refine units of encapsulation refine units of encapsulation – By adding or By adding or overriding overriding methods methods – By adding attributes By adding attributes
  • 4.
    4 4 Inheritance Inheritance Notation Notation Java.awt.Dialog Java.awt.Dialog Java.awt.FileDialog Java.awt.FileDialog Base Class Base Class (orParent Class (or Parent Class or Superclass) or Superclass) Derived Class Derived Class (or Child Class (or Child Class or Subclass) or Subclass) Is-a relationship Is-a relationship
  • 5.
    5 5 Dynamic Method Binding DynamicMethod Binding • Consequence of inheritance Consequence of inheritance – derived class derived class D D has all members of its base class has all members of its base class B B – can use an object of class can use an object of class D D everywhere an object of class everywhere an object of class B B is expected is expected » a form of polymorphism a form of polymorphism • Example (C++): Example (C++): class person { ... }; class person { ... }; class student : public person { ... }; class student : public person { ... }; class professor : public person { ... }; class professor : public person { ... }; student s; student s; professor p; professor p; ... ... person * x = &s; person * x = &s; person * y = &p; person * y = &p; // Both // Both student student and and professor professor objects have all properties of objects have all properties of // a // a person person object object // Both can be used in a // Both can be used in a person person context context
  • 6.
    6 6 Dynamic Method Binding DynamicMethod Binding • Example (C++): Example (C++): class person { ... }; class person { ... }; class student : public person { ... }; class student : public person { ... }; class professor : public person { ... }; class professor : public person { ... }; void person::print_mailing_label () { ... } void person::print_mailing_label () { ... } student s; student s; professor p; professor p; ... ... person * x = &s; person * x = &s; person * y = &p; person * y = &p; s.print_mailing_label (); s.print_mailing_label (); p.print_mailing_label (); p.print_mailing_label (); // person::print_mailing_label () // person::print_mailing_label () // person::print_mailing_label () // person::print_mailing_label ()
  • 7.
    7 7 Dynamic Method Binding DynamicMethod Binding • Example (C++): Example (C++): – Suppose that we redefine Suppose that we redefine print_mailing_label print_mailing_label in both derived classes in both derived classes void student::print_mailing_label () { ... } void student::print_mailing_label () { ... } void professor::print_mailing_label () { ... } void professor::print_mailing_label () { ... } student s; student s; professor p; professor p; ... ... person * x = &s; person * x = &s; person * y = &p; person * y = &p; s.print_mailing_label (); s.print_mailing_label (); p.print_mailing_label (); p.print_mailing_label (); // student ::print_mailing_label () // student ::print_mailing_label () // professor ::print_mailing_label () // professor ::print_mailing_label () – But what about: But what about: x->print_mailing_label (); x->print_mailing_label (); // ?? // ?? y->print_mailing_label (); y->print_mailing_label (); // ?? // ??
  • 8.
    8 8 Dynamic Method Binding DynamicMethod Binding – Two alternatives for choosing the Two alternatives for choosing the method to call: method to call: » according to the types of variables (references) according to the types of variables (references) x x and and y y – – static method binding static method binding (will call the method of (will call the method of person person in both cases) in both cases) » according to the types of objects according to the types of objects s s and and p p to which to which x x and and y y refer – refer – dynamic dynamic method binding method binding (will call the methods of (will call the methods of student student / / professor professor) ) – Dynamic method binding – central issue to object-oriented programming Dynamic method binding – central issue to object-oriented programming – Example – list of Example – list of persons persons that have overdue library books that have overdue library books » list may contain both list may contain both students students and and professors professors » traverse the list and print a mailing label - call the appropriate subroutine traverse the list and print a mailing label - call the appropriate subroutine • Example (C++): Example (C++): student s; student s; professor p; professor p; ... ... person * x = &s; person * x = &s; person * y = &p; person * y = &p; x->print_mailing_label (); x->print_mailing_label (); // ?? // ?? y->print_mailing_label (); y->print_mailing_label (); // ?? // ??
  • 9.
    9 9 Dynamic Method Binding DynamicMethod Binding • Simula, C++, Ada 95 Simula, C++, Ada 95 – static method binding by default static method binding by default – run-time overhead run-time overhead • Smalltalk, Modula-3 Smalltalk, Modula-3 – dynamic method binding dynamic method binding • Java, Eiffel Java, Eiffel – dynamic method binding by default dynamic method binding by default – individual methods can be labeled individual methods can be labeled final final (Java) or (Java) or frozen frozen (Eiffel) (Eiffel) » cannot be overriden by derived classes cannot be overriden by derived classes » use static method binding use static method binding • Disadvantage of dynamic method binding Disadvantage of dynamic method binding – how do we specify dynamic binding in C++? how do we specify dynamic binding in C++? » label individual methods as label individual methods as virtual virtual
  • 10.
    10 10 Virtual and Non-VirtualMethods Virtual and Non-Virtual Methods • C++ C++ class person class person { { public: public: virtual void print_mailing_label (); virtual void print_mailing_label (); ... ... } } – if if print_mailing_label print_mailing_label is overridden in classes is overridden in classes student student and and professor professor » at run time, the appropriate one is chosen – dynamic binding at run time, the appropriate one is chosen – dynamic binding • Terminology in C++: Terminology in C++: – redefine redefine a method that uses static binding a method that uses static binding – override override a method that uses dynamic binding a method that uses dynamic binding
  • 11.
    11 11 Virtual and Non-VirtualMethods Virtual and Non-Virtual Methods • Ada Ada – methods take as parameter the object they are applied to methods take as parameter the object they are applied to – dynamic binding is associated not with the method but with the parameter dynamic binding is associated not with the method but with the parameter – here, here, r r needs to be declared as needs to be declared as person'Class person'Class → → dynamic binding dynamic binding
  • 12.
    12 12 Virtual and Non-VirtualMethods Virtual and Non-Virtual Methods • Static method binding is more efficient Static method binding is more efficient • When could it be undesirable? When could it be undesirable? – May not preserve consistency in the derived class May not preserve consistency in the derived class – Example: Example: class text_file class text_file { { char * name; char * name; long crt_pos; long crt_pos; public: public: void seek (long pos); void seek (long pos); // non-virtual // non-virtual ... ... }; }; class read_ahead_text_file : public text_file class read_ahead_text_file : public text_file { { char * upcoming_chars; char * upcoming_chars; public: public: void seek (long pos); void seek (long pos); // redefinition // redefinition // also updates the // also updates the upcoming_chars upcoming_chars ... ... }; }; – with static binding: with static binding: » text_file::seek text_file::seek may be called for a may be called for a read_ahead_text_file read_ahead_text_file object, if used where object, if used where text_file text_file was expected was expected » state of the state of the read_ahead_text_file read_ahead_text_file object would become inconsistent object would become inconsistent
  • 13.
    13 13 Abstract Classes Abstract Classes •C++ C++ class person class person { { ... ... public: public: virtual void print_mailing_label () = 0; virtual void print_mailing_label () = 0; ... ... }; }; – Abstract method Abstract method – virtual method with no body – virtual method with no body » also called also called pure virtual method pure virtual method in C++ in C++ – Abstract class Abstract class – it has at least one abstract method – it has at least one abstract method » cannot declare objects of an abstract class, just pointers cannot declare objects of an abstract class, just pointers – Purpose of an abstract class: Purpose of an abstract class: » serve as base to derive serve as base to derive concrete classes concrete classes » a a concrete class concrete class must provide a definition for every abstract method it inherits must provide a definition for every abstract method it inherits – Interface Interface (Java) – (Java) – class with no other members than abstract methods class with no other members than abstract methods
  • 14.
    14 14 Member Lookup Member Lookup •Static method binding: Static method binding: – easy to find the method to call, based on the type of the variable easy to find the method to call, based on the type of the variable – performed at compile time performed at compile time • Dynamic method binding Dynamic method binding – appropriate method is identified at run-time appropriate method is identified at run-time – objects must contain information to allow for finding the appropriate objects must contain information to allow for finding the appropriate method method – each object contains a pointer to a each object contains a pointer to a virtual method table virtual method table ( (vtable vtable) ) – all objects of a given class have the same all objects of a given class have the same vtable vtable
  • 15.
    15 15 Member Lookup Member Lookup –The compiler will generate: The compiler will generate: • Implementation of a Implementation of a vtable vtable: : – Consider the code: Consider the code: foo * f; foo * f; f->m(); f->m(); – Runtime overhead (compared to static binding) – two instructions Runtime overhead (compared to static binding) – two instructions
  • 16.
    16 16 Member Lookup Member Lookup •When defining a derived class: When defining a derived class: – Ordering is essential: Ordering is essential: » all new members introduced by all new members introduced by bar bar must appear at the end: must appear at the end: » additional data members ( additional data members (w w) at the end of the record ) at the end of the record » additional virtual methods ( additional virtual methods (s s and and t t) at the end of the ) at the end of the vtable vtable » virtual methods overridden in virtual methods overridden in bar bar (such as (such as m m) – appear in ) – appear in bar bar's 's vtable vtable at the at the same place as in same place as in foo foo's 's vtable vtable
  • 17.
    17 17 Member Lookup Member Lookup •Allowed operations (same example): Allowed operations (same example): class foo { ... }; class foo { ... }; class bar : public foo { ... }; class bar : public foo { ... }; ... ... foo F; foo F; bar B; bar B; foo * q; foo * q; bar * s; bar * s; q = &B; q = &B; // // s = &F; s = &F; // // ok; references through ok; references through q q will use prefixes of will use prefixes of B B's data space and 's data space and vtable vtable static semantic error; static semantic error; F F lacks the additional data and lacks the additional data and vtable vtable entries of a entries of a bar bar
  • 18.
    18 18 Type Checking Type Checking stillan error still an error ok, but risky – programmer must ensure that ok, but risky – programmer must ensure that q q refers to a refers to a bar bar object object C++ specific – involves dynamic type check C++ specific – involves dynamic type check • C++ C++ class foo { ... }; class foo { ... }; class bar : public foo { ... }; class bar : public foo { ... }; – Type correctness of the code above – checked statically Type correctness of the code above – checked statically foo F; foo F; bar B; bar B; foo * q; foo * q; bar * s; bar * s; ... ... q = &B; q = &B; s = &F; s = &F; s = q; s = q; // // – But it can be done: But it can be done: s = (bar*) q; s = (bar*) q; // // – Better solution: Better solution: s = dynamic_cast<bar*> (q); s = dynamic_cast<bar*> (q); // //
  • 19.
    19 19 Type Checking Type Checking •Java Java – allows only the "classic" cast, but with dynamic check allows only the "classic" cast, but with dynamic check • Eiffel Eiffel class foo ... class foo ... class bar inherit foo ... class bar inherit foo ... ... ... f : foo; f : foo; b : bar; b : bar; ... ... f := b; f := b; -- always ok -- always ok b ?= f; b ?= f; -- reverse assignment, with dynamic check -- reverse assignment, with dynamic check – Reverse assignment Reverse assignment ?= ?= assigns an object reference into a variable only if assigns an object reference into a variable only if the type at run-time is acceptable the type at run-time is acceptable » b b gets gets f f if if f f refers to a refers to a bar bar object at run-time object at run-time » otherwise otherwise b b gets gets nil nil
  • 20.
    20 20 Type Checking –Implementation Type Checking – Implementation • Eiffel, Java, C++ Eiffel, Java, C++ – what is needed to perform dynamic checking? what is needed to perform dynamic checking? » run-time run-time type descriptor type descriptor included in the object representation included in the object representation • Smalltalk Smalltalk – variables are untyped references variables are untyped references – data members are never public data members are never public – any assignment is legal any assignment is legal – only method invocation ("send a message") is dynamically checked only method invocation ("send a message") is dynamically checked » implementation – dictionary that maps method names to their code implementation – dictionary that maps method names to their code » run-time – lookup in dictionary to check if method is supported run-time – lookup in dictionary to check if method is supported » if not – dynamic semantic error if not – dynamic semantic error – comparison to C++ approach: comparison to C++ approach: » more flexible in Smalltalk more flexible in Smalltalk » less efficient – increased run-time cost less efficient – increased run-time cost » delayed reporting of errors delayed reporting of errors
  • 21.
    21 21 Member Lookup Member Lookup •Disadvantages of virtual methods: Disadvantages of virtual methods: – run-time cost run-time cost – preclude in-line expansion of methods at compile time preclude in-line expansion of methods at compile time » performance decrease for small and frequently called methods performance decrease for small and frequently called methods • Potential problem with static lookup: Potential problem with static lookup: – fragile base class fragile base class problem (Java): problem (Java): » large standard library, evolving over time (adding new features) large standard library, evolving over time (adding new features) » user may have old library and run code designed for new library user may have old library and run code designed for new library » code may use the new features code may use the new features » static lookup static lookup – invalid memory access – invalid memory access » dynamic lookup dynamic lookup – better, produce error message ("member not found") – better, produce error message ("member not found")
  • 22.
    22 22 Classes as "Closures" Classesas "Closures" • Classes – can implement a mechanism similar to Classes – can implement a mechanism similar to first-class first-class subroutines subroutines
  • 23.
    23 23 Classes as "Closures" Classesas "Closures" • Advantage of latter version (with classes): Advantage of latter version (with classes): – can also add data members to class can also add data members to class bar bar (and object (and object my_obj my_obj) ) – function function f f can use them can use them – similarity between: similarity between: » data members of an object with a virtual method, data members of an object with a virtual method, AND AND » referencing environment of a referencing environment of a closure closure in a language with nested scopes in a language with nested scopes • Application: Application: – discrete event simulation discrete event simulation – need to have a subroutine need to have a subroutine schedule_at schedule_at that: that: » takes as parameters a time value and a function takes as parameters a time value and a function f f (to be called at that time) (to be called at that time) » function function f f should have an arbitrary set of parameters should have an arbitrary set of parameters – how do we pass such a function how do we pass such a function f f (with ANY number of parameters)? (with ANY number of parameters)? » pass a "closure" instead – implemented with classes pass a "closure" instead – implemented with classes
  • 24.
    24 24 Classes as "Closures" Classesas "Closures" • Example - discrete event simulation: Example - discrete event simulation:

Editor's Notes

  • #2 Emphasis on why O-O PLs support these features