LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 7

An override that extends the base implementation Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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

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

struct Logger {
    virtual std::string format(const std::string& m) const { return "[log] " + m; }
    virtual ~Logger() = default;
};
struct TimeLogger : Logger {
    std::string format(const std::string& m) const override { return "10:30 " + Logger::format(m); }
};
struct LoudLogger : TimeLogger {
    std::string format(const std::string& m) const override { return TimeLogger::format(m) + "!"; }
};

int main() {
    LoudLogger l;
    const Logger& g = l;
    std::cout << g.format("disk full") << '\n';
    return 0;
}
  • A 10:30 [log] disk full! Correct
  • B [log] disk full
  • C 10:30 [log] disk full
  • D [log] disk full!
Correct Answer: Option A

The call dispatches to LoudLogger::format, which calls TimeLogger::format, which calls Logger::format – qualified calls are not re-dispatched, so each level adds its part once.

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