How do I make a deep copy constructor on member variables?

I am really stuck here. From what I have read online a deep copy constructor copies what is in the pointer (prob not exactly what it is). I have looked at code online but seems overly complex for my application.Any way I know this forum is not a code writing service but if someone can show me deep constructor for my use and explain the code that would be greatly appreciated. I am really desperate for a solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 #pragma once
#include <string>
#include <iostream>

using namespace std;
//Artist Class Definition.
class Artist
{
public:
	//Defualt Constructer 
	Artist::Artist();
	// Getter Function.
	string getName();
	string getCountry();
	// Set Function
	void setName(string);
	void setCountry(string);
	~Artist();
	Artist&Artist::operator=(const Artist& p);

private:
	string *firstName;
	string country;
};



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <string>
#include <iostream>
#include <fstream>
#include "artist.h"

using namespace std;

//Default Constructer
Artist::Artist() {
	//Now a pointer.
	*firstName = "";
	country = "";
}


//Deep Copy constructer?



//Artist& Artist::operator=(const Artist& p) {
		//firstName = p.firstName;  
		//return *this;
	
//}//end operator=

//Deconstructer
Artist::~Artist() {
	delete firstName;
	firstName = NULL;
}
//Set & Get Functions
void Artist::setName(string f) {
	*firstName = f;
}

void Artist::setCountry(string c) {
	country = c;
}

string Artist::getName() {
	return *firstName;
}
string Artist::getCountry() {
	return country;
}
If you have a pointer that is a member of a class, then all that pointer is, is a variable that stores an address to a block of computer memory.

If you were to make a shallow copy of that class...

say myClass2 = myClass1 for example, you end up with a new instance of the original class that has a pointer storing the same address of computer memory as the original class. So if you were to change the value of the pointer in myClass1, the pointer in myClass2 is also affected since both pointers are attached to the same address.

A deep copy will allow you to create a copy of myClass1 but give a new separate address to its pointer.

https://owlcation.com/stem/Copy-Constructor-shallow-copy-vs-deep-copy
Last edited on
Topic archived. No new replies allowed.