Pure Virtual Functions and Abstract Classes in C++

Sometimes implementation of all functions cannot be provided in a base class because we don’t know the implementation. Such a class is called an abstract class. For example, let Shape be a base class. We cannot provide an implementation of function draw() in Shape, but we know every derived class must have an implementation of draw(). Similarly, an Animal class doesn’t have an implementation of the move() (assuming that all animals move), but all animals must know how to move. We cannot create objects of abstract classes.
A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration. See the following example.
// An abstract class
class Test
{   
    // Data members of class
public:
    // Pure Virtual Function
    virtual void show() = 0;
    
   /* Other members */
};

A complete example:
A pure virtual function is implemented by classes which are derived from a Abstract class. Following is a simple example to demonstrate the same.

#include<iostream>
using namespace std;
  
class Base
{
   int x;
public:
    virtual void fun() = 0;
    int getX() { return x; }
};
  
// This class inherits from Base and implements fun()
class Derived: public Base
{
    int y;
public:
    void fun() { cout << "fun() called"; }
};
  
int main(void)
{
    Derived d;
    d.fun();
    return 0;
}
Output:
fun() called


Post a Comment

0 Comments