Early binding and Late binding in C++
Binding
refers to the process of converting identifiers (such as variable and
performance names) into addresses. Binding is done for each variable and
functions.It takes place either at compile time or at runtime.
Fig: Early binding and Late binding in C++ |
1. Early Binding (compile-time time polymorphism)
Early binding as the name indicates, compiler (or linker) directly
associate an address to the function call. It replaces the call with a machine
language instruction that tells the mainframe to leap to the address of the
function. This can be achieved by declaring virtual function.
Program:
#include<iostream.h>
#include<conio.h>
class
Base
{
public:
virtual void show()
{
cout<<”base
class /n”;
}
};
class
Derived: public Base
{
public:
void
show()
{
cout<<”derived
class /n”
}
};
void
main()
{
Base
*bp=new Derived;
bp->show();
}
Output:
Base
class
2. Late Binding : (Run time polymorphism)
In this, the compiler adds code that identifies the kind of
object at runtime then matches the call with the right function definition .This
can be achieved by declaring virtual function.
Program:
#include<iostream.h>
#include<conio.h>
class
Base
{
public:
virtual void show()
{
cout<<”base
class /n”;
}
};
class
Derived: public Base
{
public:
void
show()
{
cout<<”derived
class /n”
}
};
void
main()
{
Base
*bp=new Derived;
bp->show();
}
Output:
derived
class
No comments:
Post a Comment