ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
struct Base {
Base() { cout << "B "; }
virtual ~Base() { cout << "~B "; }
};
struct Derived : Base {
int* data;
Derived() : data(new int[10]) { cout << "D "; }
~Derived() override { delete[] data; cout << "~D "; }
};
int main() {
Base *arr[2];
arr[0] = new Derived();
arr[1] = new Derived();
for (auto p : arr) delete p;
}- A. B D B D ~D ~B ~D ~B
- B. B D B D ~B ~D ~B ~D
- C. B D D B ~D ~B ~D ~B
- D. Memory leak: data is never freed because ~Derived is never called
Correct answer: A. B D B D ~D ~B ~D ~B
Both Derived objects are constructed first (B D, B D). Because Base's destructor is virtual, deleting each Base* correctly invokes the full chain starting at Derived: for each pointer, ~Derived runs first (freeing data, printing ~D) then ~Base (~B), in the order the loop processes arr[0] then arr[1].
More OOP with C++ and Java questions
- What is printed? java class Converter<T, R> { R convert(T input, java.util.function.Function<T, R> fn) { return fn.apply(input); } } // in…
- What is printed? cpp template<typename T> T maxVal(T a, T b) { return a > b ? a : b; } class Money { int cents; public: Money(int c)…
- What is printed? cpp class Shape { public: virtual void draw() const = 0; }; class Group : public Shape { vector<Shape> children; public…
- What is printed? java class Base { public int hashCode() { return 1; } } class Derived extends Base { @Override public int hashCode() {…
- What is printed? java class Base { Base self() { return this; } } class Derived extends Base { @Override Derived self() { return this; }…
- What is printed? java class Account { private double balance; Account(double b) { balance = b; } void withdraw(double amt) { if (amt >…