A tough concept question I faced in a revision C++ class was the question of virtual vs pure virtual function. Here we discuss the virtual vs pure virtual function c++.
What is a Virtual Function in C++?
A virtual function is a function that can be overridden within an inheriting class by a function with the same name. A pure virtual function is required to be implemented by a derived class, that is not abstract.
The virtual keyword gives C++ the ability to support polymorphism.
What is a Pure Virtual Function in C++?
Pure virtual functions are used for:
- Abstract classes are base classes where you have to derive from them and then implement the pure virtual functions
- Interfaces consist of empty classes where all functions are purely virtual, hence you have to derive and then implement all of the functions
So in simple English – The virtual function can be overridden and a pure virtual function must be implemented.
Sample of a pure virtual function. The “= 0” portion of a pure virtual function is also known as the pure specifier, because it’s what makes a pure virtual function “pure”.
class A { public: virtual void pure_virtual() = 0; // a pure virtual function // note that there is no function body };
How is an object with virtual functions stored in memory C++?
Your program’s compiler generates a vtable for each object class your program implements, indicating where that object class’s functions are located. A virtual (inheritable) function on an object is invoked by utilizing the vtable, which the compiler locates and jumps to using the object’s data members.
More on cppbetterexplained: