DYNAMIC BINDING

Dynamic binding is less powerful than pointers-to-functions, but more comprehensible & less error-prone
i.e., since the compiler performs type checking at compile-time

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 ();
However, at run-time this invocation actually invokes more specialized methods implemented in a derived class, e.g.,
class Derived : public Base
{ public: virtual int vf (void); };
Derived d;
bp = &d;
bp->vf (); // invokes Derived::vf()
The answer depends on the type of binding used…
  • 1. Static Binding
: the compiler uses the type of the pointer to
perform 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)

Efficiency vs. flexibility are the primary tradeoffs between static & dynamic binding Static binding is generally more efficient since
1. It has less time & space overhead
2. It also enables method inlining
Dynamic binding is more flexible since it enables developers to
extend the behavior of a system transparently
However, dynamically bound objects are difficult to store in shared memory

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..
}

POINTER TO OBJECT;

QUE- IMPLEMENT A LOGIC TO SHOW THE USE OF POINTER TO OBJECT;

ANS-

#include<iostreAm.h>
#include<conio.h>
class dep
{
public:
int a;
void print()
{
cout<<“\nValue of a is = “<<a;
}
};
int main()
{
dep s, *s1;
s1=&s; //pointer to object
int dep::*ptr=&dep::a; //pointer to member using scope resolution
s.*ptr=10;
s.print();
s1->*ptr=20; //method to access ptr member
s1->print();
cout<<“\n\nPROGRAMMING AT C#ODE STUDIO”;
getch();
}

ptr_obj

CONSTRUCTORS

que- implement a logic to show how you can use constructor;

answer-

#include<iostream.h>
#include<conio.h>
using namespace std;
class student
{
private:
int marks1,marks2;
public:
student(int a, int b) //HERE WE DEFINE THE INSTRUCTION//
{
marks1=a;
marks2=b;
}
void disp();
};
void student::disp()
{
if(marks1>marks2)
{
cout<<“\nSTUDENT 1 GOT HIGHER MARKS: “<<marks1<<endl;
}
else
{
cout<<“\nSTUDENT 2 GOT HIGHER MARKS: “<<marks2<<endl;
}
}
int main()
{
int i,j;
cout<<“\nINPUT 1ST STUDENT’S MARKS:”;
cin>>i;
cout<<“\nINPUT 2ND STUDENT’S MARKS:”;
cin>>j;
student s(i,j); //On the initializing object to class constructor got executed;
s.disp();
cout<<“\n\nPROGRAMMING AT C#ODE STUDIO”;
getch();
}

constructor_scope