Deep copy of pointers

Hi,

A class called Pair and its member variables int* pa and int* pb have already been created. I am trying to do a deep copy of pointer pa and pb. Please see my code below and help me check if my code is correct. Many thanks!!


class Pair {
public:
int *pa,*pb;
Pair(int, int);
Pair(const Pair &);
~Pair();
}

Pair::Pair(int, int){
int a;
int b;
Pair(a, b);
int *pa = new int;
int *pb = new int;
*pa = a;
*pb = b;
}

Pair::Pair(const Pair & q){
int a;
int b;
Pair(a, b);
int *pa = new int;
int *pb = new int;
*pa = *q.pa;
*pb = *q.pb;
}

Pair::~Pair(){
delete pa;
pa = nullptr;
delete pb;
pb = nullptr;
}
Use code tags:



[code]

//Your Code Here

[/code]



You're code looks fine so far, though I don't see any deep copying happening. A deep copy would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
	int *first = new int(12);
	int *second = new int(9);


	//to do first = second:
	*first = *second; //Value of first becomes the value of second

	//first = second -> this is a shallow copy,
	//the memory address of second becomes the memory address of first

	//Will Output different memory addresses
	std::cout << first << '\n' << second;
}
Topic archived. No new replies allowed.