The matching of a function call by the C++ compiler with the correct function definition at run time is called dynamic binding. However, to implement dynamic binding, the concept of virtual functions is important.
Let's understand the concept of dynamic binding with the help of the following example-
#include <iostream.h>
#include <conio.h>
class animal
{
public:
void eat();
void sleep();
void breathe();
};
class fish : public animal
{
public:
void breathe();
};
void animal :: eat()
{
cout << "Eating..." <eat();
pointer = &bigfish;
pointer->eat();
getch();
return 0;
}
In the preceding code snippet, if a pointer holds a pointer to an animal class object and you use it to call eat, animal::eat \MII be called. However, if a pointer holds a pointer to a fish cla^s object and you use it to call eat, fish::eat will be called, not animai::eat. Using late binding, the program determines about the members of a class to which a pointer points at the runtime, not at the compile time.
Let's understand the concept of dynamic binding with the help of the following example-
#include <iostream.h>
#include <conio.h>
class animal
{
public:
void eat();
void sleep();
void breathe();
};
class fish : public animal
{
public:
void breathe();
};
void animal :: eat()
{
cout << "Eating..." <
pointer = &bigfish;
pointer->eat();
getch();
return 0;
}
In the preceding code snippet, if a pointer holds a pointer to an animal class object and you use it to call eat, animal::eat \MII be called. However, if a pointer holds a pointer to a fish cla^s object and you use it to call eat, fish::eat will be called, not animai::eat. Using late binding, the program determines about the members of a class to which a pointer points at the runtime, not at the compile time.
No comments:
Post a Comment