CJCoding With Joseph
15per day
← Back to Question List

Select topics to narrow your question pool, then enable Random to jump to a random question matching your filters.

Topics:
C++ Quiz #34

Shallow Copy Bug

mediumRule of Three

This code crashes when the objects are destroyed. What is the bug in the copy constructor?

📄 Code

1#include <iostream>
2using namespace std;
3 
4class Array {
5public:
6 int* data;
7 int size;
8 Array(int s) : size(s) {
9 data = new int[size];
10 }
11 Array(const Array& other) {
12 size = other.size;
13 data = other.data; // copy the pointer
14 }
15 ~Array() { delete[] data; }
16};
17 
18int main() {
19 Array a(5);
20 a.data[0] = 99;
21 Array b = a;
22 cout << b.data[0] << endl;
23 return 0;
24}