LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 20

One class implementing two interfaces Answer, explanation & discussion

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

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

main.cpp
#include <iostream>

struct Printable { virtual void print() const = 0; virtual ~Printable() = default; };
struct Savable   { virtual bool save() const = 0;  virtual ~Savable() = default; };

struct Invoice : Printable, Savable {
    int no = 42;
    void print() const override { std::cout << "Invoice #" << no << ' '; }
    bool save() const override { std::cout << "saved "; return true; }
};

void show(const Printable& p) { p.print(); }
bool store(const Savable& s) { return s.save(); }

int main() {
    Invoice inv;
    show(inv);
    std::cout << store(inv) << '\n';
    return 0;
}
  • A Invoice #42 saved 1 Correct
  • B Invoice #42 1
  • C saved Invoice #42 1
  • D Compilation error
Correct Answer: Option A

Invoice implements both pure abstract interfaces, so it can be passed to code expecting either. Interfaces without data make multiple inheritance safe and simple.

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