Difference Between a Virtual Function and a Pure Virtual Function in C++



In C++, virtual and pure virtual functions are key features supporting polymorphism both allow different classes to respond uniquely to the same function call.

What is Virtual Function

A virtual function in C++ is a member function in a base class, which allows a function to be overridden in the derived class. This process helps in enabling runtime polymorphism. A virtual function is declared in the base class using the virtual keyword.

Syntax

Following is the syntax of the virtual function:

class BaseClassName {
public:
   virtual void func_name() {
      // implementation
   }
};

Implementation of Virtual Function

In the following example, we demonstrate the working of the virtual function:

#include <iostream>
using namespace std;
class B {
 public:
virtual void s() {
 cout<<" In Base \n";
}
};

class D: public B {
 public:
void s() {
 cout<<"In Derived \n";
}
};

int main(void) {
 D d; // An object of class D
 B *b= &d;// A pointer of type B* pointing to d
 b->s();// prints"D::s() called"
 return 0;
}

Following is the output of the above code:

In Derived

What is Pure Virtual Function?

A pure virtual function is a virtual function, it has no definition in a base class, serving as a placeholder that must be overridden in derived classes. It is declared by assigning = 0 in its declaration.

Syntax

Following is the syntax of the pure virtual function:

class baseClass {
public:
   virtual returnType name_of_function() = 0;
};

Implementation of Pure Virtual Function

In the following example, we demonstrate the working of the pure virtual function:

#include<iostream>
using namespace std;
class B {
 public:
virtual void s() = 0; // Pure Virtual Function
};

class D:public B {
 public:
void s() {
 cout << " Virtual Function in Derived class\n";
}
};

int main() {
 B *b;
 D dobj; // An object of class D
 b = &dobj;// A pointer of type B* pointing to dobj
 b->s();// prints"D::s() called"
}

Following is the output of the above code:

Virtual Function in Derived class

Difference between a Virtual Function and a Pure Virtual Function

The table below shows the difference between Virtual and Pure Virtual Function:

Sr.No Virtual Function
Pure Virtual Function
1 Virtual function has their definition in the class.
Pure virtual function has no definition.
2 Declaration: virtual funct_name(parameter_list) {. . . . .};
Declaration: virtual funct_name(parameter_list)=0;
3 It has no concept of derived class.
If a class contains at least one pure virtual function, then it is declared abstract.
4 If required, the base class can override a virtual function.
In case of pure virtual function derived class has to definitely override the pure virtual function.
Updated on: 2025-06-18T18:40:06+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements