When objects of different classes in a class hierarchy, react to the same message in their own unique ways, they are said to exhibit polymorphic behavior. The following demonstrate the need for virtual functions.
It has the base class Father and the derived class Son and has a member function with the same and prototype. Note that, in C++ a pointer to the base class can be used to point to its derived class objects.
Sample Program
#include <iostream.h>
class Father
{
char name[40];
public:
Father(char *fname)
{
strcpy(name, fname);
}
void show(void)
{
cout<<”Father Name is “<<name<<endl;
}
};
class Son : public Father
{
char name[20];
public:
Son(char *sname, char *fname) : Father(fname)
{
strcpy(name, sname);
}
void show(void)
{
cout<<”Son Name is”<<name<<endl;
}
};
void main()
{
Father *Fp;
Father f1(“Thomas”);
Fp = &f1;
Fp->show();
Son s1(“Thomas”, “Martin”);
Fp = &s1;
Fp->show();
}
when executing this program the output will be same as “Thomas” for both of the show functions. There must be a provision to use the member function Show() to display the state of objects of both the Father and Son classes the same interface. This decision cannot be taken by the compiler, since the prototype is identical in both the cases.
In C++ a function call can be bound to the actual function either at compile time or at runtime. Resolving a function call at compile time is known as Compile-Time or Early or Static Binding whereas, resolving a function call at runtime is known as Runtime or Late or Dynamic Binding.
Runtime Ploymorphism allows to postpone the decision of selecting the suitable member functions until runtime. In C++, this is achieved by using Virtual Functions.
Sample Program
#include <iostream.h>
class Father
{
char name[20];
public:
Father(char *fname)
{
strcpy(name,fname);
}
virtual void show(void)
{
cout<<”Father name”<<name<<endl;
}
};
class Son:public Father
{
char name[30];
public:
Son(char *sname, char *fname):Father(fname)
{
strcpy(name,sname);
}
void show(void)
{
cout<<”Son name is”<<sname<<endl;
}
};
void main()
{
Father *fp;
Father f1(“James”);
fp = &f1;
fp->show();
Son s1(“James”,”Vasanth”);
fp = &s1;
fp->show();
}
the knowledge of pointers to base class and derived classes is essential to understand and to explore full potential of virtual functions.
No comments:
Post a Comment