← 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;
}
- A.Derived Derived
- B.Base Base
- C.Base Derived
- 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 →