Early (static) binding and late (dynamic) binding in C++

Early Binding:

Choosing a function in normal way, during compilation time is called as early binding or static binding or static linkage. During compilation time, the C++ compiler determines which function is used based on the parameters passed to the function or the function’s return type. The compiler then substitutes the correct function for each invocation. Such compiler based substitutions are called static linkage. Whatever functions discussed so far in the earlier chapters, are based on static binding only.

By default, C++ follows early binding. With early binding, one can achieve greater efficiency. Function calls are faster in this case because all die information necessary to call the function are hard coded.

The purest object oriented programming language like small talk permits only run time binding of the methods, whereas C++ allows both compile time binding and run time binding. In that sense, C++ is a hybrid language as it generates the code of both procedural and object oriented programming paradigm.

Late Binding:

Choosing functions during execution time is called late binding or dynamic binding or dynamic linkage. Late binding requires some overhead but provides increased power and flexibility. The late binding is implemented through virtual functions. An object of a class must be declared either as a pointer to a class or a reference to a class.

For example, the following declaration of the virtual function shows how a late binding or run time binding can be carried out:

class base A {
private:
int x;
float y;
public:
virtual void display ();
int sum ();
};
class derivedD : public baseA
{
private:
int x;
float y;
public:
void display(); // virtual
int sum();
};
void main()
{
baseA *ptr;
derivedD objd;
ptr = &objd;
ptr->display(); //run time binding
ptr-> sum(); //compile time binding
}

The keyword virtual must be followed by a return type of a member function if a runtime is to be bound. Otherwise, the compile time binding will be effected as usual. In the above program segment, only the display () function has been declared as virtual in the base class, whereas the sum () is non virtual. Even though the message is given from the pointer of the base class to the objects of the derived class, it will not access the sum () function of the derived class as it has been declared as non virtual. The sum () function compiles only the static binding.

Subscribe / Share

Article by Admin

Authors bio is coming up shortly. Read 528 articles by Admin
It's very calm over here, why not leave a comment?

Leave a Reply

You must be logged in to post a comment.