LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Predict the Output · Question 13

Overriding a hook with a default implementation Answer, explanation & discussion

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

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

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

class Parser {
public:
    std::string parse(const std::string& line) const { return before() + body(line) + after(); }
    virtual ~Parser() = default;
protected:
    virtual std::string body(const std::string& line) const = 0;
    virtual std::string before() const { return "<"; }
    virtual std::string after() const { return ">"; }
};
struct Csv : Parser {
    std::string body(const std::string& l) const override { return std::to_string(l.size()); }
};
struct Json : Parser {
    std::string body(const std::string& l) const override { return "\"" + l + "\""; }
    std::string before() const override { return "{"; }
    std::string after() const override { return "}"; }
};

int main() {
    std::cout << Csv{}.parse("a,b,c") << ' ' << Json{}.parse("ok") << '\n';
    return 0;
}
  • A <5> {"ok"} Correct
  • B <5> <"ok">
  • C 5 "ok"
  • D <a,b,c> {"ok"}
Correct Answer: Option A

body() is pure and must be supplied; before()/after() are ordinary virtual hooks with defaults that Json overrides.

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