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);
}- A. Report: Q1Report: Q2
- B. Compilation error: cannot store unique_ptr<Report> in vector<unique_ptr<Printable>>
- C. Report: Q2Report: Q1
- 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
- What is printed? java class Shape implements Comparable<Shape> { double area; Shape(double a) { area = a; } public int compareTo(Shape o)…
- What is printed? java class Base { public Object process() { return "base-result"; } } class Derived extends Base { @Override public…
- What is printed? cpp class Logger { public: static Logger& instance() { static Logger inst; return inst; } void log(const string& msg) {…
- What is printed? java class EventBus { private static EventBus instance; private EventBus() { System.out.print("created "); } public…
- What is printed? java class Base { Base clone2() { return new Base(); } } class Derived extends Base { @Override Derived clone2() { return…
- What is printed? java class Animal { void makeSound() { System.out.print("..."); } } class Dog extends Animal { @Override void makeSound()…