LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 11

dynamic_cast to a reference that fails Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 Back to Exercise

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

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

struct Media { virtual ~Media() = default; };
struct Song  : Media { int seconds = 210; };
struct Photo : Media {};

int seconds_of(const Media& m) {
    try {
        return dynamic_cast<const Song&>(m).seconds;
    } catch (const std::bad_cast&) {
        return -1;
    }
}

int main() {
    Song s;
    Photo p;
    std::cout << seconds_of(s) << ' ' << seconds_of(p) << ' ' << (typeid(p) == typeid(Photo)) << '\n';
    return 0;
}
  • A 210 -1 1 Correct
  • B 210 0 1
  • C 210 -1 0
  • D The program crashes
Correct Answer: Option A

A failed dynamic_cast to a reference throws std::bad_cast (a pointer cast would return nullptr). typeid on a polymorphic object reports its dynamic type.

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