Virtual Functions in OOP's:

Virtual means existing in effect but not in reality. A virtual function is one that does not really exist but nevertheless appears real to some parts of the program. Virtual functions provide a way for a program to decide when it is running, what function to call. The virtual function allows greater flexibility in performing the same kinds of action, on different kind of objects. While using virtual functions:



a. It should be a member function of a class.
b. Static member functions cannot be virtual functions.
c. A virtual function should be declared in the base class specifications.

d. A virtual function may or may not have function body.
e. Virtual functions can be overloaded.
f. Constructors cannot be declared as virtual functions.
g. There can be virtual destructors.




Write a program to explain virtual functions.
#include<iostream.h>
class baseclass
{
public:
void putdata()
{
cout<<”\n this is base class:”;
}
};
class derivedclass1 : public baseclass
{
public:
void putdata()
{
cout<<”\n This is derived class1:”;
}
};
class derivedclass2 : public baseclass
{
public :
void putdata()
{
cout<<”\n This is derived class2:”;
}
};
void main()
{
derivedclass1 d1;
derivedclass2 d2;
baseclass *ptr;
ptr->putdata();
ptr=&d1;
ptr->putdata();
ptr=&d2;
ptr->putdata();
}


Output:
This is a base class:
This is derived class1:
This is derived class2:





Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: