Skip to main content

Command Palette

Search for a command to run...

🔹 Abstract Class and Pure Virtual Function in C++ (Beginner-Friendly Guide)

Published
3 min readView as Markdown

📌 Introduction

In C++, sometimes we want to define rules but do not want to provide the implementation in the base class.
In such cases, we use Abstract Classes and Pure Virtual Functions.

These concepts are a core part of Object-Oriented Programming (OOP).


🔹 The Problem with a Normal Class

class Animal {
public:
    void sound() {
        cout << "Animal sound" << endl;
    }
};

Why is this a problem?

Every animal has a different sound:

  • Dog → Bark

  • Cat → Meow

  • Cow → Moo

The base class cannot decide the exact behavior.


🔹 Solution: Pure Virtual Function

Definition:

A Pure Virtual Function is a virtual function that:

  • Has no implementation in the base class

  • Must be implemented by the derived (child) class


🔹 Syntax of a Pure Virtual Function

virtual void functionName() = 0;

= 0 means:

“This function has no body here.
Derived classes must implement it.”


🔹 Example of a Pure Virtual Function

class Animal {
public:
    virtual void sound() = 0;   // Pure virtual function
};

This means:

Every animal must make a sound,
but how it sounds will be decided by the child class.


🔥 What Is an Abstract Class?

Definition:

A class that contains at least one pure virtual function is called an Abstract Class.

Important Rule:

Animal a;   // ❌ Error

❌ You cannot create an object of an abstract class.


🔹 Relationship Between Abstract Class and Pure Virtual Function

Pure Virtual Function
        ↓
Class becomes incomplete
        ↓
Class becomes ABSTRACT
        ↓
Object cannot be created
        ↓
Derived class must implement the function

🔹 Implementing the Pure Virtual Function (Child Class)

class Dog : public Animal {
public:
    void sound() {
        cout << "Dog barks" << endl;
    }
};

✔ Rule is followed
✔ Class becomes complete (concrete class)

Dog d;
d.sound();   // Output: Dog barks

🔹 What If the Child Class Does NOT Implement It?

class Cat : public Animal {
    // sound() not implemented
};

❌ Error
👉 Cat also becomes an abstract class


🔹 Example Using Polymorphism

int main() {
    Animal* a;
    Dog d;

    a = &d;
    a->sound();   // Calls Dog's sound()
}

Output:

Dog barks

✔ This is runtime polymorphism


🔹 Abstract Class vs Normal Class

FeatureNormal ClassAbstract Class
Object creationAllowed❌ Not allowed
Function bodyAlways presentMay be missing
Pure virtual function❌ No✅ Yes
PurposeImplementationRule / blueprint

More from this blog

Amit singh's blog

235 posts