Abstract Classes &
Pure Virtual Functions
Learn how C++ uses abstract classes and pure virtual functions to define interfaces, enforce contracts, and unlock the power of polymorphism.
What Is a Virtual Function?
A virtual function is a member function in a base class that you can override in a derived class. When called through a base-class pointer or reference, C++ determines at runtime which version to invoke: this is called dynamic dispatch.
From Virtual to Pure Virtual
A pure virtual function has no body in the base class. Instead of providing a default implementation, you append = 0 to the declaration. This tells derived classes: "you must implement this."
What Is an Abstract Class?
Any class that contains at least one pure virtual function automatically becomes an abstract class. You cannot create objects of an abstract class directly: it exists only to be inherited from.
The Inheritance Hierarchy
The Core Rule
Abstract vs Concrete Classes
| Abstract Class | Concrete Class | |
|---|---|---|
| Pure virtual functions | At least one | None (all implemented) |
| Can be instantiated? | No | Yes |
| Pointers/references? | Yes | Yes |
| Purpose | Define an interface | Provide full behavior |
| Can have data members? | Yes | Yes |
Why Use Abstract Classes?
How to Apply This Pattern
Example 1: Abstract Shape
Example 2: Concrete Circle
Example 3: Polymorphism in Action
What If You Don't Override?
A derived class remains abstract until every inherited pure virtual function has been overridden.
Surprise: Pure Virtual with a Body
C++ allows you to provide a default implementation for a pure virtual function. The class is still abstract, but derived classes can optionally call the base version.
Common Mistakes to Avoid
Summary at a Glance
| Concept | Syntax / Rule | Effect |
|---|---|---|
| Virtual function | virtual void f(); | Can be overridden; dynamic dispatch |
| Pure virtual | virtual void f() = 0; | Must be overridden; class becomes abstract |
| Abstract class | Has ≥ 1 pure virtual | Cannot be instantiated |
| Concrete class | Overrides all pure virtuals | Can be instantiated |
| override keyword | void f() override; | Compiler checks correct override |
Question 1 of 5
What makes a C++ class abstract?
Question 2 of 5
Given the following code, which statement is true?
Question 3 of 5
If class B inherits from abstract class A but does not override all pure virtual functions, what happens?
Question 4 of 5
Which of the following is a valid use of an abstract class?
Question 5 of 5
Why should an abstract base class have a virtual destructor?