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; }- A. It is correct: the implicit copy constructor allocates a new array
- B. Copying shares p, so both destructors delete the same array: undefined behaviour
- C. It leaks memory because the destructor never runs for b
- 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
- What is printed? cpp struct A { int x; A(int v) : x(v) { } }; struct B : A { int y; B(int v) : A(v 2), y(x + 1) { } }; int main() { B…
- What is printed? cpp struct B { B() { cout << "b"; } ~B() { cout << "~b"; } }; struct D : B { D() { cout << "d"; } ~D() { cout << "~d"; }…
- What is printed? cpp struct X { int v; X(int a) : v(a) { } bool operator==(const X& o) const { return v == o.v; } }; int main() { X a(1)…
- What happens? cpp class Shape { public: virtual double area() const = 0; }; class Square : public Shape { double s = 2; double area()…
- What is printed? cpp struct Counter { int n = 0; Counter& add(int k) { n += k; return this; } Counter addCopy(int k) { n += k; return…
- Which statement about virtual functions and templates in C++ is correct?