♠ Posted by Unknown in CPP Language at 04:07
Virtual Function
When we use the same function name in both the
base and derived classes, the function in base class id declared as virtual
using virtual preceding its
normal declaration.
When a function is made virtual, C++ determines which function to use at run time base on the type of object pointed to by the bas pointer, rather than the type of the pointer. Thus, by making the base pointer to point to different objects, we can execute different versions of the virtual function.
When a function is made virtual, C++ determines which function to use at run time base on the type of object pointed to by the bas pointer, rather than the type of the pointer. Thus, by making the base pointer to point to different objects, we can execute different versions of the virtual function.
Example:
#include<iostream.h>
#include<conio.h>
class Base
{
public:
void
display()
{
cout<<"\nDisplay Base : "; }
virtual
void show()
{
cout<<"\nShow Base : "; }
};
class Derived : public Base
{
public:
void
display()
{
cout<<"\nDisplay Derived : "; }
void
show()
{
cout<<"\nShow Derived : "; }
};
void main()
{
Base B;
Derived
D;
Base
*bptr;
cout<<"\nbptr points to Base
\n";
bptr =
&B;
bptr->display(); //calls Base Version
bptr->show(); //Calls Base Version
cout<<"\n\n bptr points to
Derived\n";
bptr =
&D;
bptr->display(); //Calls Base Version
bptr->show(); //Calls Derived Version
}
0 comments:
Post a Comment