Difference Between Virtual and Pure Virtual Function

Computer ProgrammingProgrammingMiscellaneous

In this post, we will understand the difference between virtual and pure virtual functions.

Virtual Function

  • It has its own definition inside the class.

  • The base class can override a virtual function.

  • It doesn’t have a derived class.

Declaration

virtual funct_name(parameter_list) {. . . . .};

Pure Virtual Function

  • It doesn’t have a definition.

  • If a class has at least one virtual function, it can be declared abstract.

  • The derived class has to override the pure virtual function to use it.

  • A pure virtual function is specified by placing "= 0" in its declaration

Declaration

virtual funct_name(parameter_list)=0;

Following is an example −

Example

class Box {
   public:
   // pure virtual function
   virtual double getVolume() = 0;
   private:
   double length; // Length of a box
   double breadth; // Breadth of a box
   double height; // Height of a box
};
raja
Published on 24-Mar-2021 18:39:57
Advertisements