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";
}
}- A. Square
- B. NotSquare
- C. Compile-time error: dynamic_cast cannot be used in an if-condition
- 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
- What is printed? java class Base { void process() { System.out.print("Base.process "); validate(); } protected void validate() {…
- What is printed? java class Base { public String toString() { return "Base[" + describe() + "]"; } protected String describe() { return…
- What is printed? cpp struct A { A() { cout << "A"; } }; struct B { B() { cout << "B"; } }; struct C : A, B { C() { cout << "C"; } }; int…
- What is printed? cpp struct Animal { virtual std::string sound() const { return "..."; } }; struct Dog : Animal { std::string sound()…
- What is printed? cpp struct Shape { virtual double area() const = 0; void report() const { std::cout << "Area: " << area(); } }; struct…
- What is the behavior? cpp struct Base { ~Base() { std::cout << "~Base "; } // NOT virtual }; struct Derived : Base { int data = new…