Dynamic binding

Jan 9, 2014 at 7:44am
Hi All,

Lets say I have follwing code

class Base
{
public:
virtual void display()
{
cout<<"Derived"<<endl;
}
};

class Derived: public Base
{
public:
void display()
{
cout<,"Derived"<<endl;
}
};

int main()
{
base*bptr=new derived();
bptr->display();
return 0;
}

Even without compiling the code I can say which display this code will execute.
Then why we call this a run time polumorpshim or dynamic binding? when I could figure out which function would be executed without even compiling?


It seems to be very basic doubt but unable to figure out whats actually the difference between static and dynamic binding.whenever I use polymorphism wither static or dynamic binding I can say before compiling the code what function would be executed with each statement....Please help


Thanks in advance
Jan 9, 2014 at 8:23am
Sure, you can tell by looking but that doesn't necessarily mean that the program automatically knows which to use.

As far as its concerned, bptr is a pointer to a base type. On that information alone, you can assume that it knows only to use the base implementation of the display method.

We need to dynamically bind - through use of the virtual keyword - so that we can use the appropriate derived method of the class at runtime, even though the pointer is pointing to a base class.

Just take the virtual keyword away to see what I mean. You also may want to change the content of the base display method for clarity.
Jan 9, 2014 at 10:01am
> Lets say I have follwing code
> ...
> Even without compiling the code I can say which display this code will execute.

Now let us say, you have the following code:

A header file
1
2
3
4
5
6
7
8
9
/////////////  file base.h /////////////

// include guard

struct base
{
    virtual ~base() {}
    virtual void display() const = 0 ;
};


And an implementation file:
1
2
3
4
5
6
7
8
/////////////  file use_base.cc /////////////

#include "base.h"

void foo( const base* p ) 
{
    p->display() ; // can you say which display this code will execute?
}


Jan 9, 2014 at 10:13am
@JLBorges
@iHutch105

I understood the difference now .Thanks a lot.
Yoy guys in this forum are aloooott helpful and know much more than any c++ programmer I thought would kow.
Topic archived. No new replies allowed.