Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Why Is a C++ Pure Virtual Function Initialized by 0



In C++, the pure virtual function is initialized with = 0 to indicate that it must be overridden by the derived class and has no implementation in the base class.

A pure virtual function is a virtual function in C++ declared in a base class that has no implementation within that class.

Why Initialize by 0?

The following are the reasons for initializing by 0:

1. Mark The Function as "Pure Virtual"

  • The = 0 syntax tells the compiler that the function must be overridden by any derived class.
  • The base class cannot be instantiated if it has at least one pure virtual function.

2. Signals That There's no Implementation

  • Unlike regular virtual functions, pure virtual function do not provide a default implementation in the base class.
  • The derived class is forced to defined the function.

3. Ensures Abstract Behaviour

  • A class containing one pure virtual function becomes an abstract class.
  • Abstract class can not be instantiated, it make sure the structure of interface like classes.

Example to implement a pure virtual function

In the following example, we implement a pure virtual function:

#include <iostream>
using namespace std;

class AbstractClass {
public:
   // Pure virtual function
   virtual void show() = 0;
};

class Derived : public AbstractClass {
public:
   void show() override {
      cout << "Implementation in Derived class" << endl;
   }
};

int main() {
   Derived obj;
   obj.show();
   return 0;
}

Following is the output:

Implementation in Derived class

Example of using pure virtual functions and abstract classes

Here is another example in C++ of using pure virtual functions and abstract classes:

#include <iostream>
using namespace std;

class Payment {
   public:
      // Pure virtual function
      virtual void processPayment(double amount) = 0;
};

class CreditCard: public Payment {
   public: void processPayment(double amount) override {
      cout << "Processing Credit Card Payment of $" << amount << endl;
   }
};

int main() {
   Payment * payment1;
   CreditCard cc;

   payment1 = & cc;
   payment1 -> processPayment(100.50);

   return 0;
}

Following is the output:

Processing Credit Card Payment of $100.5
Updated on: 2025-05-16T17:10:40+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements