LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Predict the Output · Question 14

Cross-casting between interfaces with dynamic_cast Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 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 Exportable { virtual int export_size() const = 0; virtual ~Exportable() = default; };

struct Report : Printable, Exportable {
    void print() const override { std::cout << "report "; }
    int export_size() const override { return 42; }
};
struct Note : Printable {
    void print() const override { std::cout << "note "; }
};

void handle(const Printable& p) {
    p.print();
    if (auto* e = dynamic_cast<const Exportable*>(&p)) std::cout << e->export_size() << ' ';
    else std::cout << "- ";
}

int main() {
    handle(Report{});
    handle(Note{});
    std::cout << '\n';
    return 0;
}
  • A report 42 note - Correct
  • B report - note -
  • C report 42 note 42
  • D Compilation error
Correct Answer: Option A

dynamic_cast can cast "sideways" from one interface to another when the complete object implements both; for Note it returns nullptr.

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