LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Predict the Output · Question 10

Creating implementations through a factory 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 <string>

struct Codec {
    virtual std::string encode(const std::string& s) const = 0;
    virtual ~Codec() = default;
};
struct Caesar : Codec {
    std::string encode(const std::string& s) const override {
        std::string r = s;
        for (char& c : r) if (c >= 'a' && c <= 'z') c = static_cast<char>('a' + (c - 'a' + 3) % 26);
        return r;
    }
};
struct Reverse : Codec {
    std::string encode(const std::string& s) const override { return {s.rbegin(), s.rend()}; }
};

std::unique_ptr<Codec> make(char k) {
    if (k == 'c') return std::make_unique<Caesar>();
    return std::make_unique<Reverse>();
}

int main() {
    std::cout << make('c')->encode("xyz") << ' ' << make('r')->encode("xyz") << ' '
              << make('c')->encode(make('r')->encode("abc")) << '\n';
    return 0;
}
  • A abc zyx fed Correct
  • B abc zyx def
  • C xyz zyx fed
  • D abc xyz fed
Correct Answer: Option A

Caesar shifts by 3 with wrap-around (x→a, y→b, z→c). The last call reverses "abc" to "cba" and then shifts it to "fed".

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