LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Predict the Output · Question 16

A class template implementing an interface Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

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

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

struct Value {
    virtual std::string str() const = 0;
    virtual ~Value() = default;
};

template <typename T>
struct Boxed : Value {
    T v;
    explicit Boxed(T x) : v(x) {}
    std::string str() const override {
        if constexpr (std::is_same_v<T, bool>) return v ? "true" : "false";
        else return std::to_string(v);
    }
};

int main() {
    std::vector<std::unique_ptr<Value>> row;
    row.push_back(std::make_unique<Boxed<int>>(7));
    row.push_back(std::make_unique<Boxed<bool>>(true));
    row.push_back(std::make_unique<Boxed<long>>(-3));
    for (const auto& v : row) std::cout << v->str() << ';';
    std::cout << '\n';
    return 0;
}
  • A 7;true;-3; Correct
  • B 7;1;-3;
  • C 7;true;3;
  • D Compilation error
Correct Answer: Option A

Each instantiation of Boxed is a different concrete class implementing the same interface – templates and interfaces combine naturally.

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