Back to questions
JuniorTheoryCommon
What does the program print?
#include <iostream>
struct Shape {
virtual int sides() const { return 0; }
};
struct Circle : public Shape {};
struct Square : public Shape {};
int main() {
Square sq;
Shape* p = &sq;
std::cout << (dynamic_cast<Circle*>(p) == nullptr) << '\n';
}1
- Expecting
0:dynamic_castchecks the real type of the object at run time, andppoints to aSquare, not aCircle, so the result isnullptr. - Expecting undefined behavior:
dynamic_castnever converts to a wrong type; when the object does not match,dynamic_castreturnsnullptrinstead.
- What would
dynamic_cast<Square*>(p)return here? - Why does this
dynamic_caststop compiling ifsidesis notvirtual?