LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Predict the Output · Question 2

One object seen through two interfaces Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

struct Reader { virtual int read() = 0; virtual ~Reader() = default; };
struct Writer { virtual void write(int x) = 0; virtual ~Writer() = default; };

struct Buffer : Reader, Writer {
    int data[4]{}; int r = 0, w = 0;
    int read() override { return r < w ? data[r++] : -1; }
    void write(int x) override { if (w < 4) data[w++] = x; }
};

int main() {
    Buffer b;
    Writer& out = b;
    Reader& in = b;
    out.write(7); out.write(8);
    std::cout << in.read() << ' ' << in.read() << ' ' << in.read() << '\n';
    return 0;
}
  • A 7 8 -1 Correct
  • B 8 7 -1
  • C 7 8 0
  • D 7 7 7
Correct Answer: Option A

Both references refer to the same Buffer object, each through a different interface.

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