ProgrammingHardProduct-company placement · C++
What is wrong with this program?
What is wrong with this program?
struct Buf {
int* p;
Buf() : p(new int[4]) { }
~Buf() { delete[] p; }
};
int main() { Buf a; Buf b = a; }- A. Nothing; the implicit copy constructor duplicates the array
- B. The implicit copy shares the pointer, so the same array is deleted twice: undefined behaviour
- C. It fails to compile because Buf has no copy constructor
- D. Only a memory leak: b's array is never freed
Correct answer: B. The implicit copy shares the pointer, so the same array is deleted twice: undefined behaviour
The compiler-generated copy constructor copies the pointer value (shallow copy). Both destructors then delete[] the same block. The Rule of Three: a class that needs a destructor usually also needs a copy constructor and copy assignment (or must delete them).
More OOP with C++ and Java questions
- What happens when this is compiled? cpp struct A { int v = 0; int& get() const { return v; } };
- A global object g1 defined in file1.cpp uses the global object g2 defined in file2.cpp inside g1's constructor. Both have dynamic…
- What is printed? cpp void f(int) { cout << "I"; } void f(char) { cout << "P"; } int main() { f(0); f(nullptr); }
- Which lines fail to compile? cpp void g(int& x) { } void h(const int& x) { } int main() { int a = 1; g(5); // L1 h(5); // L2 g(a); // L3…
- What is printed? cpp void f(int&) { cout << "N"; } void f(const int&) { cout << "C"; } int main() { int a = 1; f(a); f(5); }
- What is printed? cpp void f(int&) { cout << "L"; } void f(int&&) { cout << "R"; } int main() { int a = 1; int&& r = 5; f(a); f(5)…