0
0
C++programming~5 mins

Abstract classes in C++

Choose your learning style9 modes available
Introduction

Abstract classes let you create a base blueprint that other classes must follow. They help organize code by forcing certain functions to be made in child classes.

When you want to define a common interface for different types of objects.
When you want to make sure certain functions are implemented in all child classes.
When you want to share some code but also require specific details in subclasses.
When you want to prevent creating objects of the base class directly.
When designing a system with different behaviors but shared structure.
Syntax
C++
class AbstractClassName {
public:
    virtual void pureVirtualFunction() = 0; // pure virtual function
    void normalFunction() {
        // some code
    }
    virtual ~AbstractClassName() {}
};

A pure virtual function is declared by adding = 0 at the end.

Abstract classes cannot be instantiated directly.

Examples
This abstract class Shape forces all shapes to have a draw function.
C++
class Shape {
public:
    virtual void draw() = 0; // must be implemented by child classes
    virtual ~Shape() {}
};
Circle implements the required draw function.
C++
class Circle : public Shape {
public:
    void draw() override {
        // code to draw a circle
    }
};
Even if the implementation is empty, draw must be defined.
C++
class EmptyShape : public Shape {
public:
    void draw() override {
        // empty implementation
    }
};
Sample Program

This program shows an abstract class Animal with a pure virtual function makeSound. The classes Dog and Cat implement this function. Trying to create an Animal object directly would cause an error.

C++
#include <iostream>

class Animal {
public:
    virtual void makeSound() = 0; // pure virtual function
    virtual ~Animal() {}
};

class Dog : public Animal {
public:
    void makeSound() override {
        std::cout << "Woof!" << std::endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        std::cout << "Meow!" << std::endl;
    }
};

int main() {
    // Animal animal; // Error: cannot instantiate abstract class

    Dog dog;
    Cat cat;

    std::cout << "Dog says: ";
    dog.makeSound();

    std::cout << "Cat says: ";
    cat.makeSound();

    return 0;
}
OutputSuccess
Important Notes

Time complexity depends on the implementation of the functions in child classes.

Abstract classes use a small amount of extra memory for the virtual table pointer.

Common mistake: Trying to create an object of the abstract class directly causes a compile error.

Use abstract classes when you want to enforce a contract for subclasses, instead of using regular classes or interfaces alone.

Summary

Abstract classes define functions that child classes must implement.

They cannot be instantiated directly.

They help organize code and enforce rules for subclasses.