1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. Base's constructor calls a virtual function that Derived…

Added 30 Nov -0001

Base's constructor calls a virtual function that Derived overrides, and a Derived object is being constructed. Which version runs?

  1. The program fails to compile, because virtual calls in constructors are illegal and are always rejected by every conforming compiler
  2. Derived's version, because the dynamic type of the object is already Derived from the moment the allocation completes
  3. Base's version, because during base construction the vptr still refers to Base's vtable and the Derived part does not yet exist Correct answer
  4. It is undefined behaviour, so either version may run depending on the compiler and on the optimisation level used

Correct answer

C. Base's version, because during base construction the vptr still refers to Base's vtable and the Derived part does not yet exist

18 views

MCQSEXAM

Explanation

Virtual dispatch during construction is limited to the class whose constructor is running, since the derived members are not yet initialised. The same restriction applies in destructors, where the dynamic type reverts as each level is torn down. Calling a pure virtual function from a constructor is worse: it is undefined behaviour and usually aborts with a pure virtual call error.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is C? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs