Dynamic binding allows applications to be written by invoking general methods via a base class pointer, e.g.,
class Base { public: virtual int vf (void); }; Base *bp = /* pointer to a subclass */; bp->vf ();
class Derived : public Base { public: virtual int vf (void); }; Derived d; bp = &d; bp->vf (); // invokes Derived::vf()
- 1. Static Binding
: the compiler uses the type of the pointer toperform the binding at compile time. Therefore,Vector::operator[](vp, 0)will be called
- 2. Dynamic Binding
: the decision is made at run-time based upon
the type of the actual object.
Checked
Vector::operator[]
will be called in this case as
(*vp->vptr[1])(vp, 0)
1. It has less time & space overhead2. It also enables method inliningDynamic binding is more flexible since it enables developers toextend the behavior of a system transparently–
EXAMPLE –
class Base
{
public:
virtual void Op();
}
class Derived: public Base
{
public:
void Op()
{
cout << "Output through Derived!" << endl;
}
}
main
{
Base * pB = new Derived();
pB->Op(); //dynamic binding, uses virtual table lookup at run time..
}