Virtual function

A virtual function is a member function which is declared within base class and is re- defined by derived class.In other worf we can say that you except to be redefined in derived classes. Function are declared with a virtual keyword is base class. It is used to tell the compiler to perform dynamic linkage or late binding on the function.

Rules for virtual function :

  • Virtual functions must be members of some class.
  • Virtual functions cannot be static members.
  • They are accessed through object pointers.
  • They can be a friend of another class.
  • A virtual function must be defined in the base class, even though it is not used.
  • The prototype of virtual functions should be same in base as well as derived class.

syntax:

class class name
{
public:
virtual void function name ()
{
.................................................
................................................. [body of virtual function]
}
};

Example : Problem without virtual keyword :

Here we are going to write a program without using virtual keyword.

#include< iostream.h >
class base
{
public:
void area()
{
int ar, h=20,w=30;
ar=h*w;
cout<< "Base class : area =" << a;
}
};
class derived:public base
{
public:
void area()
{
int ar, h=20,w=30;
ar=h*w;
cout<< "derived class : area =" << a;
}
};
void main()
{
base* obj1; // base class pointer
derived obj2; // derived class object
obj2->area(); // early binding ocuurs
}

Output:

Base class : area = 600

Example : With virtual keyword

Here we are going to write a program using virtual keyword.

#include< iostream.h >
class base
{
public:
virtual void area()
{
int ar, h=20,w=30;
ar=h*w;
cout<< "Base class : area =" << a;
}
};
class derived:public base
{
public:
void area()
{
int ar, h=20,w=30;
ar=h*w;
cout<< "derived class : area =" << a;
}
};
void main()
{
base* obj1; // base class pointer
derived obj2; // derived class object
obj1=&obj2;
obj->area(); // early binding ocuurs
}

Output:

Base class : area = 600

Pure virtual function

A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in the declaration. In other word we can say that it is a function that is declare inside a base class. Which has no definition relative to the base class. In these classes that define the function or declare it as a pure virtual function.

Pure Virtual Function can be declared as:

virtual void area() = 0;
#include< iostream.h >
class base
{
public:
virtual void area() = 0;
};
class derived:public base
{
public:
void area()
{
int ar, h=20,w=30;
ar=h*w;
cout<< "derived class : area =" << a;
}
};
void main()
{
base* obj1; // base class pointer
derived obj2; // derived class object
obj1=&obj2;
obj->area(); // early binding ocuurs
}

Output:

derived class : area = 600