ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Printable {
public:
    virtual void print() const = 0;
    virtual ~Printable() = default;
};
class Report : public Printable {
    string title;
public:
    Report(string t) : title(std::move(t)) {}
    void print() const override { cout << "Report: " << title; }
};
void printAll(const vector<unique_ptr<Printable>>& items) {
    for (const auto& item : items) item->print();
}
int main() {
    vector<unique_ptr<Printable>> items;
    items.push_back(make_unique<Report>("Q1"));
    items.push_back(make_unique<Report>("Q2"));
    printAll(items);
}
  1. A. Report: Q1Report: Q2
  2. B. Compilation error: cannot store unique_ptr<Report> in vector<unique_ptr<Printable>>
  3. C. Report: Q2Report: Q1
  4. D. It crashes due to slicing

Correct answer: A. Report: Q1Report: Q2

unique_ptr<Derived> implicitly converts to unique_ptr<Base> on push_back (ownership-transferring move), so this compiles fine and stores polymorphic pointers without slicing. printAll iterates and calls print() virtually on each, giving "Report: Q1" then "Report: Q2" in insertion order.

More OOP with C++ and Java questions

Exams that ask this topic