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.
Abstract classes in 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.
Shape forces all shapes to have a draw function.class Shape { public: virtual void draw() = 0; // must be implemented by child classes virtual ~Shape() {} };
Circle implements the required draw function.class Circle : public Shape { public: void draw() override { // code to draw a circle } };
draw must be defined.class EmptyShape : public Shape { public: void draw() override { // empty implementation } };
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.
#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; }
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.
Abstract classes define functions that child classes must implement.
They cannot be instantiated directly.
They help organize code and enforce rules for subclasses.