Early Binding When a binding is performed before the program is run

Late Binding Binding occurs at run time ( also late binding , dynamic binding )

VTABLE

VPTR

// Explanation
// If u assign a derived clas object ( here flute ) to
// a base class type variable . and call the member function
// then the base class memeber function is called although
// the obj var has derived class object in it

// this is overcome by addding keyword "virtual" in the base class
// member function definition. By adding the keyword "virtual" the
// the compiler is forced to do a "Late Binding"

 

//: C15:Instrument3.cpp
// Late binding with the virtual keyword
#include <iostream>
using namespace std;
enum note { middleC, Csharp, Cflat }; // Etc.

class Instrument
{
    public:
    virtual void play(note) const
    {
        cout << "Instrument::play" << endl;
    }
};

// Wind objects are Instruments
// because they have the same interface:
class Wind : public Instrument
{
    public:
    // Override interface function:
    void play(note) const
    {
        cout << "Wind::play" << endl;
    }
};

void tune(Instrument& i)
{
    // ...
    i.play(middleC);
}

int main()
{
    Wind flute;
    tune(flute); // Upcasting
} ///:~

 

 

Tip 1:

Each time you create a class that contains virtual functions, or you

derive from a class that contains virtual functions, the compiler

creates a unique VTABLE for that class,

 

Tip 2: Fortunately, the compiler takes care of all the

bookkeeping for you and ensures that all the function pointers in

all the VTABLEs of a particular class hierarchy occur in the same

order, regardless of the order that you may override them in

derived classes.

 

Tip 3 : This is where creation of the default constructor is essential. In the

Instrument examples, the compiler creates a default constructor

that does nothing except initialize the VPTR. This constructor, of

course, is automatically called for all Instrument objects before you

can do anything with them, so you know that it’s always safe to call

virtual functions.

 

Hosted by www.Geocities.ws

1