🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Inheritance and Virtual Functions: all 10 questions

Quiz: Inheritance and Virtual Functions · Question 6 of 10

What does this print? (code)

What does this print?

#include <iostream>
#include <string>
using namespace std;
struct B { virtual string name() const { return "Base"; } };
struct D : B { string name() const override { return "Derived"; } };
void byValue(B b) { cout << b.name() << " "; }
void byRef(const B &b) { cout << b.name() << "\n"; }
int main() {
    D d;
    byValue(d);
    byRef(d);
    return 0;
}
  1. A.Derived Derived
  2. B.Base Base
  3. C.Base Derived
  4. D.Derived Base
Answer & explanation

Correct answer: Base Derived

Passing by value copies only the B part (object slicing), so the base version runs; a reference keeps the real object.

Can you get the rest right without peeking?

Take the timed Quiz: Inheritance and Virtual Functions quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →