C++ pointers and inheritance: which statement is correct regarding pointers to base and derived classes?

Difficulty: Easy

Correct Answer: Derived class pointer cannot point to base class.

Explanation:


Introduction / Context:
Pointer conversions in inheritance hierarchies are fundamental for polymorphism. Correctly understanding which implicit conversions are allowed avoids type-unsafe code and undefined behavior. This question contrasts upcasting (derived to base) with the invalid notion of pointing a derived pointer at a base object.


Given Data / Assumptions:

  • Simple single inheritance is assumed for clarity.
  • We consider implicit pointer conversions without casts.
  • Objects are properly constructed of the indicated types.


Concept / Approach:

A pointer to a base can point to an object of a derived class (upcast), because every derived object contains a base subobject. However, the reverse is not true: a pointer to a derived class cannot safely point to a base object (downcast) without a checked mechanism, because the base object lacks the additional derived parts. Implicit conversion from base* to derived* is illegal. Therefore, the correct statement is that a derived class pointer cannot point to a base class object.


Step-by-Step Solution:

Establish rule: implicit upcast derived* → base* is allowed. Establish rule: implicit downcast base* → derived* is not allowed. Map to options: “Derived class pointer cannot point to base class.” matches the rule. Choose option B.


Verification / Alternative check:

Code sample: Base b; Base* pb = &b; Derived* pd = pb; // error. But Derived d; Base* p = &d; // OK. Using dynamic_cast with a polymorphic base can attempt downcasts safely at runtime, returning nullptr on failure.


Why Other Options Are Wrong:

“Base pointer cannot point to derived” is false; that is exactly what enables polymorphism.

“Pointer to derived cannot be created” and “Pointer to base cannot be created” are nonsense; both can be declared.


Common Pitfalls:

  • Using C-style casts to force downcasts unsafely.
  • Forgetting to make the base class polymorphic (virtual destructor) before using dynamic_cast on pointers/references.


Final Answer:

Derived class pointer cannot point to base class.

More Questions from OOPS Concepts

Discussion & Comments

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