1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. void f(Base b); is called as f(derivedObject); where…

Added 30 Nov -0001

void f(Base b); is called as f(derivedObject); where Derived publicly derives from Base and both override a virtual print(). What does b.print() call inside f?

  1. Base::print, because object slicing copies only the Base sub-object into the parameter Correct answer
  2. It is undefined behaviour, so either version may run depending on the optimisation level
  3. Derived::print, because the argument's dynamic type stays Derived inside the function
  4. Derived::print if Base's destructor is virtual, else Base::print, since dispatch depends on it

Correct answer

A. Base::print, because object slicing copies only the Base sub-object into the parameter

14 views

MCQSEXAM

Explanation

Object slicing occurs when a derived object is copied into a base value parameter, so the parameter is a genuine Base object and virtual dispatch finds Base::print. Passing by reference, Base& b, preserves the dynamic type and calls Derived::print. The same slicing happens when derived objects are stored by value in a std::vector<Base>.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is A? 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