Pure Virtual Functions and Abstract Classes

  • October 27, 2022
  • C++
Accessing Elements
What are Pure Virtual Functions?

A pure virtual function is a virtual function in C++ that does not require any function definition and is only declared. It is declared by assigning a value of 0 to the declaration. For instance,

virtual int Area() = 0; // Pure virtual function is declared as follows.
What is an Abstract Class?

In C++, an abstract class has at least one pure virtual function. A pure virtual function can coexist with regular functions and variables in an abstract class.

Characteristics of Abstract Class:
  • Abstract classes cannot be instantiated, but pointers and references to abstract classes can be created.
  • Abstract classes are primarily used for Upcasting, allowing derived classes to use their interface.
  • If an Abstract Class has derived classes, the derived classes must implement all pure virtual functions, or they will also become Abstract.
  • An abstract class can have constructors. 
Example:
#include<iostream>
using namespace std;
class B {
   public:
      virtual void s() = 0; // Pure Virtual Function
};

class D:public B {
   public:
      void s() {
         cout << "Virtual Function in Derived class";
      }
};

int main() {
   B *b;
   D dobj;
   b = &dobj;
   b->s();
}
Output:
Virtual Function in Derived class
Pure Virtual definitions:

Pure virtual functions can be briefly specified in the Abstract class, which will be shared by all derived classes. You are still unable to create Abstract class objects.

In addition, the Pure Virtual function must be specified independently of the class description. If you define it within the class description, the compiler will throw an error. It is illegal to define pure virtual inline.

Example:
#include<iostream>
using namespace std;

class A         
{
    public:
    virtual void show() = 0;     //Pure Virtual Function
};

void A :: show()     //Pure Virtual definition
{
    cout << "Pure Virtual definition\n";
}

class B:public A
{
    public:
    void show()
    { 
        cout << "Implementation of Virtual Function in Derived class\n"; 
    }
};

int main()
{
    A *a;
    B b;
    a = &b;
    a->show();
}
Output:
Implementation of Virtual Function in Derived class

Note: also read about Virtual Functions in C++

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *