C++ abstract classes: what is the correct way to make a class abstract (non-instantiable)?

Difficulty: Easy

Correct Answer: By making at least one member function a pure virtual function.

Explanation:


Introduction / Context:
An abstract class in C++ serves as an interface or a base with incomplete behavior. It cannot be instantiated directly; instead, derived classes complete the behavior. This is central to polymorphism and clean API design, especially when you want to enforce contracts on subclasses while sharing common infrastructure in the base.


Given Data / Assumptions:

  • A “pure virtual function” is declared with = 0 in its declaration.
  • Const member functions and the virtual keyword are distinct notions.
  • No special keyword like “abstract” exists in standard C++ to mark classes as abstract.


Concept / Approach:

A class becomes abstract if it declares (or inherits unimplemented) at least one pure virtual function, for example virtual void draw() = 0;. This signals that the base provides an interface contract but lacks an implementation. Derived classes must override the pure virtual function(s) to be instantiable. Using the virtual keyword alone does not make a function pure; it only enables dynamic dispatch. Marking functions const controls whether they can modify the object; it does not affect abstractness. There is no abstract keyword in standard C++.


Step-by-Step Solution:

Choose a function that should be overridden by derived classes. Declare it pure virtual: virtual Ret f(params) = 0; The class now cannot be instantiated directly. Derived classes must provide f(...) to become concrete.


Verification / Alternative check:

Attempt to instantiate an abstract class with a pure virtual function; the compiler emits an error. Provide an override in a derived class and instantiate that; compilation succeeds, confirming the mechanism.


Why Other Options Are Wrong:

All functions constant — unrelated to abstractness.

static keyword — unrelated; affects storage linkage, not abstractness.

virtual keyword by itself — enables polymorphism but does not make a function pure.


Common Pitfalls:

  • Forgetting to mark destructors virtual in abstract bases used polymorphically.
  • Leaving a pure virtual destructor without a definition; it still requires one if used.


Final Answer:

By making at least one member function a pure virtual function.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion