3.2.2. Virtual Functions, Dynamic Binding Through Virtual Functions, Virtual Function Call Mechanism, Pure Virtual Functions
Q18. Explain in detail about virtual functions.
Answer:
Virtual Functions
Virtual functions are the functions whose ‘declarations precede with a keyword ‘virtual’ to determine which version of a function must be invoked at the runtime. The choice of the function’s version depends upon the type of the object to which the base class pointer points. It doesn’t depend on the type of the pointer. Hence, various virtual function versions can be executed by pointing the base pointer to different objects.
Virtual functions can be accessed through the base class pointers.
Need of Virtual Functions
Virtual functions are needed in order to achieve polymorphism because a base class pointer even if it is containing the address of the derived class, is not able to execute the functions in the derived class and always runs the base class function. That is, the compiler itself chooses the member function that has the same type as the pointer thereby ignoring the contents of the pointer.
Syntax
virtual returntype functionname();
Program
#include<iostream>
using namespace std;
class base
{
private:
int x;
float y;
public:
virtual void getdata();
virtual void display();
};
class dev : public base
{
private:
int rollno;
char name[20];
public:
void getdata();
void display();
};
void base :: getdata( )
{
}
void base:: display( )
{
}
void dev :: getdata( )
{
cout<<“Enter the Roll number
of the Student:”;
cin>> rollno;
cout<<“Enter the Name of the
student:”; -
cin>>name;
}
void dev :: display( )
{
cout<<“The details of the
student are:\n”;
cout<<“Roll
no:”<<rollno <<endl;
cout<<"“Name:”<<name<<endl;
}
int main( )
{
base * ptr;
dev obj;
ptr = &obj;
ptr → getdata();
ptr → display();
return 0;
}
Output