In most of the cases, these virtual functions are defined with a null-body; it has no definition. Such functions in the base-class, are similar to do-nothing or dummy functions, they are called Pure Virtual Functions.
Pure virtual functions is declared as a virtual function with its declaration followed by = 0.
Syntax
class Myclass
{
public:
--
-- Keyword null function body
Virtual returntype Functionname (arguments) = 0;
--
--
};
A class containing pure virtual functions cannot be used to define any objects and hence such class are called pure abstract classes or abstract classes.
All other classes without pure virtual functions and which one instantiated are called as concrete classes.
Properties of Pure Virtual Function
A pure virtual function has no implementation in the base class hence, a class with pure virtual function cannot be instantiated.
It acts as an empty bucket that the derived class is supposed to fil.
A pure virtual member function can be invoked by its derived class.
//Pure virtual function with abstract class #include<iostram.h> class Absperson { public: virtual void service1 (int n); //normal virtual function virtual void service2 (int n)=0; //pure virtual function }; void Absperson :: service1 (int n) { service2 (n); } class person : public Absperson { public: void service2 (int n); }; void person :: service2 (int n) { cout<<"The number of year of service:"<<(58-n)<<end1; } void main() { Person Father, Son; Father.Service1 (50); Son.Service2 (20;) }
Output
The number of years of service = 8
The number of years of service = 38
Father-Servicel (50) – invokes the virtual function servicel ( ) defined in the Class Absperson and this in turn invokes service2 ( ). The service2 ( ) of the class person is invoked instead of Absperson.
Rules for Virtual Functions
The following rules hold good with respect to virtual functions:
- When a virtual function in a base class is created, there must be a definition of the virtual function in the base class even if base class version of the function is never actually called.
- They cannot be static members.
- They can be a friend function to another class.
- They are accessed using object pointers.
- A base pointer can serve as a pointer to a derived object since it is type compatible whereas a derived object pointer variable cannot serve as a pointer to base objects.
- Its prototype in a base class and derived class must be identical for the virtual function to work properly.
- The class cannot have virtual constructors, but can contain virtual destructor.
- Virtual functions should be declared in the public section of a class.
Read More Topics |
C++ programming basics |
Virtual base class |
Inline function in C++ |
Arithmetic assignment operation |