Open In App
Related Articles

Difference between Virtual function and Pure virtual function in C++

Improve Article
Improve
Save Article
Save
Like Article
Like

Virtual Function in C++
A virtual function is a member function which is declared within a base class and is re-defined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.

Pure Virtual Functions in C++
A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration.

Similarities between virtual function and pure virtual function

  1. These are the concepts of Run-time polymorphism.
  2. Prototype i.e. Declaration of both the functions remains the same throughout the program.
  3. These functions can’t be global or static.

Difference between virtual function and pure virtual function in C++

Virtual function Pure virtual function
A virtual function is a member function of base class which can be redefined by derived class. A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract.
Classes having virtual functions are not abstract. Base class containing pure virtual function becomes abstract.
Syntax:




virtual<func_type><func_name>()
{
    // code
}


Syntax:




virtual<func_type><func_name>()
    = 0;


Definition is given in base class. No definition is given in base class.
Base class having virtual function can be instantiated i.e. its object can be made. Base class having pure virtual function becomes abstract i.e. it cannot be instantiated.
If derived class do not redefine virtual function of base class, then it does not affect compilation. If derived class do not redefine virtual function of base class, then no compilation error but derived class also becomes abstract just like the base class.
All derived class may or may not redefine virtual function of base class. All derived class must redefine pure virtual function of base class otherwise derived class also becomes abstract just like base class.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 24 Nov, 2022
Like Article
Save Article
Similar Reads