ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
struct Shape {
    virtual ~Shape() = default;
};
struct Circle : Shape {};
struct Square : Shape {};
int main() {
    Shape *s = new Circle();
    if (Square *sq = dynamic_cast<Square*>(s)) {
        cout << "Square";
    } else {
        cout << "NotSquare";
    }
}
  1. A. Square
  2. B. NotSquare
  3. C. Compile-time error: dynamic_cast cannot be used in an if-condition
  4. D. Undefined behaviour

Correct answer: B. NotSquare

s actually points at a Circle, unrelated to Square, so dynamic_cast<Square*>(s) safely fails and yields nullptr (requires Shape to be polymorphic, which it is thanks to the virtual destructor). Initializing sq to nullptr makes the if-condition false, so the else branch runs, printing NotSquare.

More OOP with C++ and Java questions

Exams that ask this topic