Abstract classes in C++: how many objects (instances) can you directly create from an abstract class?

Difficulty: Easy

Correct Answer: Zero

Explanation:


Introduction / Context:
An abstract class is a class with at least one pure virtual function (declared with = 0). It represents an incomplete interface or behavior that must be provided by derived classes. Understanding instantiation rules for abstract classes is crucial in polymorphic design and interface-based programming.


Given Data / Assumptions:

  • The class has one or more pure virtual functions.
  • We are considering direct instantiation, e.g., Abstract a;
  • Derived classes may override all pure virtuals to become concrete.


Concept / Approach:

C++ forbids creating objects directly from an abstract class because it lacks complete behavior. However, you can create instances of derived classes that override all pure virtual functions. Polymorphic use is then achieved by referring to the concrete object through a pointer or reference to the abstract base.


Step-by-Step Solution:

Mark at least one function pure virtual: virtual void f() = 0; Attempt to instantiate: Abstract a; → compile-time error. Define Derived : public Abstract and implement f() fully. Instantiate Derived d; use Abstract&/Abstract* to access via base interface.


Verification / Alternative check:

Compile-time diagnostics clearly state that you cannot instantiate an abstract type. After implementing all pure virtuals in the derived class, instantiation succeeds, confirming the rule.


Why Other Options Are Wrong:

One/Two/As many as we want: contradict the definition—no direct instances of abstract classes are allowed.


Common Pitfalls:

  • Forgetting to implement all pure virtual functions in derived classes (including a pure virtual destructor’s definition).
  • Confusing “cannot instantiate” with “cannot have constructors” — abstract classes can have constructors for initializing shared state.


Final Answer:

Zero

More Questions from Objects and Classes

Discussion & Comments

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