ProgrammingModerateMicrosoft/Google SDE MCQ · GATE CS

Which statement about this class is correct?

Which statement about this class is correct?
struct Buf {
    int* p;
    Buf() : p(new int[8]) { }
    ~Buf() { delete[] p; }
};
void use() { Buf a; Buf b = a; }
  1. A. It is correct: the implicit copy constructor allocates a new array
  2. B. Copying shares p, so both destructors delete the same array: undefined behaviour
  3. C. It leaks memory because the destructor never runs for b
  4. D. It fails to compile, since a class with a destructor must define a copy constructor

Correct answer: B. Copying shares p, so both destructors delete the same array: undefined behaviour

The implicit copy constructor copies the pointer, not the array, so a and b both own p and delete[] runs twice. The rule of three says a class that needs a destructor usually needs a copy constructor and copy assignment too (or must delete them).

More OOP with C++ and Java questions

Exams that ask this topic