What is the output of the following C++ program on a 64-bit system?
#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 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.