In C++, which of the following cannot be declared with the keyword virtual? Select the entity for which virtual is not permitted.

Difficulty: Easy

Correct Answer: constructor

Explanation:


Introduction:
The virtual mechanism in C++ enables dynamic binding for functions invoked through base-class interfaces. This question pinpoints which constructs are compatible with virtual and which are not.


Given Data / Assumptions:

  • Language: C++.
  • Typical usage: virtual on member functions for polymorphism.
  • Special cases: constructors and destructors.


Concept / Approach:
Constructors cannot be virtual in C++ because dynamic dispatch requires an already constructed object with a valid vptr. During construction, the object’s dynamic type is not yet established for base subobjects. Destructors, on the other hand, are often virtual to ensure proper cleanup via base pointers. Member functions (non-static) can be virtual. The keyword “virtual” is not used to declare a class itself, although inheritance can be virtual in the derivation list (virtual base classes).


Step-by-Step Solution:
1) Check constructors: cannot be virtual → candidate answer.2) Check destructors: can and often should be virtual in polymorphic bases.3) Check member functions: can be virtual (enables dynamic dispatch).4) “class” is not declared virtual; instead, base-class subobjects can be specified as virtual in inheritance syntax.


Verification / Alternative check:
Compilers reject “virtual ConstructorName(...);” but accept “virtual ~Base();” and “virtual void f();”.


Why Other Options Are Wrong:
member functions: valid target for virtual.destructor: valid and recommended in interfaces.class: “virtual class” is not a declaration form; however, the question asks what cannot use virtual — the definitive, universally correct answer is the constructor.


Common Pitfalls:
Confusing “virtual inheritance” (in the derivation list) with “virtual classes.” Remember: constructors never virtual.


Final Answer:
constructor

Discussion & Comments

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