CJCoding With Joseph
15per day
← Back to Question List

Select topics to narrow your question pool, then enable Random to jump to a random question matching your filters.

Topics:
C++ Quiz #36

Object Slicing

mediumPolymorphism

The programmer expects this to print "Cat meows", but it prints "Animal speaks" instead. What went wrong?

📄 Code

1#include <iostream>
2using namespace std;
3 
4class Animal {
5public:
6 virtual void speak() {
7 cout << "Animal speaks" << endl;
8 }
9};
10 
11class Cat : public Animal {
12public:
13 void speak() override {
14 cout << "Cat meows" << endl;
15 }
16};
17 
18void makeSound(Animal a) { // pass by value
19 a.speak();
20}
21 
22int main() {
23 Cat c;
24 makeSound(c);
25 return 0;
26}