|
Binding
Object-oriented programming implements
the concept of generalization through
inheritance. A related feature offered
by C++ is late binding. This session
focuses on this feature and how it can
be used to make the code of your
program less complex and easier to
maintain.
Concept of Binding
Consider a class hierarchy to
represent the family of personal
computers. The PC class is the base
class from which the PC_XT class is
derived. The PC_XT class in turn is
the base class for PC_AT class. Figure
16.1 represents the class hierarchy.
 |
| |
|
Fig 16.1 PC Class Hierarchy |
Consider the following statements:
PC_XT Busybee;
Busybee.get_ram_space();
An object of the PC_XT class named
Busybee is created and a member
function called get_ram_space() is
invoked. To invoke the function
get_ram_space(), the compiler should
know the class to which this function
belongs. In this compiler will know
that the function get_ram_space() of
the PC_XT class is being referred. Any
member function of a class can be
invoked from the instance of that
class. In the following statement:
PC *Ptr;
….
….
Ptr->get_ram_space();
The compiler needs to associate the
get_ram_space() function with a
particular class. Here again, there is
no ambiguity. The compiler associates
the function with the PC class, based
on the pointer Ptr. Thus, the compiler
associates the function with the class
by identifying the type of the object
or pointer that is used to invoke the
function. This process of associating
a function to an object or pointer is
called binding.
In certain programming situations, the
type of the object or pointer may not
be known at the time of compilation.
For example, there may be a
requirement where a list of personal
computers needs to be created.
Depending on the request of the user,
the properties of a particular
computer, such as CPU speed, hard disk
capacity, memory space etc, may have
to be displayed. Since the objects are
dynamically created, the type of the
object is not known during compile
time. In these situations, the binding
of the function to the class is done
during run-time. This process is
called dynamic binding or late
binding.
In C++, there exists a special
relationship between the base class
and the derived class. A pointer to a
base class object can point to an
object of any of the derived class. A
pointer to a base class object can
point to an object of any of the
derived classes. For example, the PC
class in the PC family can point to an
object of the PC, PC_XT or PC_AT
class. Thus, the following assignments
are valid:
PC *Ptr;
Ptr = new PC_XT;
Ptr = new PC_AT;
|