LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 10

Cloning through a base pointer with covariant returns Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <memory>
#include <vector>

struct Unit {
    int hp;
    explicit Unit(int h) : hp(h) {}
    virtual Unit* clone() const { return new Unit(*this); }
    virtual char tag() const { return 'U'; }
    virtual ~Unit() = default;
};
struct Archer : Unit {
    using Unit::Unit;
    Archer* clone() const override { return new Archer(*this); }
    char tag() const override { return 'A'; }
};

int main() {
    std::vector<std::unique_ptr<Unit>> army;
    army.emplace_back(new Unit(50));
    army.emplace_back(new Archer(30));
    std::vector<std::unique_ptr<Unit>> copy;
    for (const auto& u : army) copy.emplace_back(u->clone());
    copy[1]->hp = 99;
    for (std::size_t i = 0; i < 2; ++i) std::cout << copy[i]->tag() << copy[i]->hp << '/' << army[i]->hp << ' ';
    std::cout << '\n';
    return 0;
}
  • A U50/50 A99/30 Correct
  • B U50/50 U99/30
  • C U50/50 A99/99
  • D A50/50 A99/30
Correct Answer: Option A

clone() is virtual, so copying through Unit* produces the right type (the Archer stays an Archer). The copies are independent: changing one does not touch the original.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links