ProgrammingVery hardProduct-company MCQ pattern
What is printed?
What is printed?
struct Animal {
virtual std::string sound() const { return "..."; }
};
struct Dog : Animal {
std::string sound() const override { return "Woof"; }
};
void printSound(Animal a) { std::cout << a.sound(); }
int main() {
Dog d;
printSound(d);
}- A. Woof
- B. Compilation error: cannot pass Dog where Animal expected
- C. Woof...
- D. ...
Correct answer: D. ...
printSound takes Animal BY VALUE, so passing a Dog slices off the Dog-specific part, copying only the Animal subobject into the parameter a. a is a true Animal at that point, so a.sound() calls Animal::sound(), printing "..." — this is the classic object-slicing bug.
More OOP with C++ and Java questions
- What is printed? cpp struct Shape { virtual double area() const = 0; void report() const { std::cout << "Area: " << area(); } }; struct…
- What is the behavior? cpp struct Base { ~Base() { std::cout << "~Base "; } // NOT virtual }; struct Derived : Base { int data = new…
- What is printed? cpp struct A { virtual void f(int x) { std::cout << "A::f(int) " << x; } }; struct B : A { virtual void f(double x) {…
- What is printed? cpp struct Base { virtual void f() const { std::cout << "Base::f const"; } }; struct Derived : Base { void f() {…
- What is printed? cpp struct IWalk { virtual void move() = 0; }; struct ISwim { virtual void move() = 0; }; struct Duck : IWalk, ISwim {…
- What is printed? cpp struct Base { static void hello() { std::cout << "Base::hello"; } }; struct Derived : Base { static void hello() {…