Object-Oriented Programming · Question 28 · Hard

What is the output of the following C++ program?

#include <iostream>
using namespace std;
class Account {
public:
    virtual void show() { cout << "Account"; }
};
class Savings : public Account {
public:
    void show() override { cout << "Savings"; }
};
void print(Account a) { a.show(); }
int main() {
    Savings s;
    print(s);
    return 0;
}
  1. Savings
  2. Compilation error
  3. Account
  4. AccountSavings
Answer and explanation

Answer: C. Account

Explanation: print takes its parameter by value, so the Savings object is copied into a plain Account object (object slicing). The copy really is an Account, so even the virtual call prints Account. Passing by reference (Account&) would print Savings.

Previous: What is the output of the following Java code? · Next: What is the output of the following Python code?

Practise object-oriented programming

Try a fresh set of object-oriented programming questions with an explanation after every answer, free and without signing up: Object-Oriented Programming practice. Or sit a full placement mock test.

More object-oriented programming questions

More technical & programming practice

DBMS · SQL · Operating Systems · Computer Networks · Software Engineering · Cloud & DevOps · GenAI Basics · Pseudo-code

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge