Removed section by SyedHC: redundant explanation of what's already explained in the "Abstract classes" section, but poorly written and incomplete, and placed ahead of more fundamental concepts, and using self-published blog as a source.
The need of the virtual function or abstract method can be understood as follows:
A class is a user-defined data type. It is used to model an identified Entity in the problem ___domain. The information required of an entity becomes fields or data members of the class, The actions required of the entity becomes member functions or methods of the class. However, in some situations, It is not possible to provide definition to one or more methods of the class. Let us understand the concept in the following scenario.
The identified Entity is Two-dimensional figure. It has two dimensions. Its area is required to be computed. Triangle, Rectangle, Square, Circle etc. are all two-dimensional figures. However the formula to compute area is different for each of the figures.
In C++, the abstract function is defined as a Pure Virtual Function.<ref>{{cite web |last1=Choudhary |first1=Syed Hafiz |title=Abstract Class in C++ |url=https://oopsinsiderguru.blogspot.com/2023/09/abstract-class-in-c.html |website=Object Oriented Languages - Insider Guru |access-date=19 September 2023}}</ref> A class is a abstract class in C++ if it at least has one pure virtual function. Now in C++, the two-dimensional figure class is implemented as follows:<syntaxhighlight lang="c++" line="1">
class TwoDFigure {
protected:
int d1;
int d2;
public:
TwoDFigure(int d1, int d2) {
this->d1 = d1;
this->d2 = d2;
}
// Pure Virtual Function
// abstract function as no definition
virtual void computeArea() = 0;
};
</syntaxhighlight>The object or an instance of abstract class cannot be created. In other words, it cannot be instantiated. It makes Inheritance and Overriding compulsory.
The concept of the virtual function solves the following problem: