ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
struct Base {
public:
virtual ~Base() { cout << "~Base "; }
};
struct Derived : Base {
int *data = new int[10];
~Derived() { delete[] data; cout << "~Derived "; }
};
int main() {
Base *p = new Derived();
delete p;
}- A. ~Base
- B. ~Derived ~Base
- C. ~Base ~Derived
- D. Nothing is printed: deleting through a Base* is undefined behaviour here
Correct answer: B. ~Derived ~Base
Because ~Base() is virtual, delete p correctly dispatches to ~Derived() first (running its cleanup and printing ~Derived), and destructors then run base-to-derived in reverse construction order, so ~Base runs afterward, printing ~Derived ~Base.
More OOP with C++ and Java questions
- What is printed? cpp struct Vehicle { virtual string type() { return "Vehicle"; } }; struct Car : Vehicle { string type() override {…
- What is printed? java abstract class Shape { abstract double area(); String describe() { return "Area=" + area(); } } class Square extends…
- What is printed? java class Base { protected String name() { return "Base"; } public String greet() { return "Hi " + name(); } } class…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { virtual void f() { cout << "B"; } }; struct C : B {…
- What is printed? java interface Flyer { default String move() { return "fly"; } } interface Swimmer { default String move() { return…
- What is printed? java class Counter { protected int count = 0; void inc() { count++; } } class LoggingCounter extends Counter { @Override…