-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeep Copy-Constructor.cpp
More file actions
51 lines (38 loc) · 1.05 KB
/
Copy pathDeep Copy-Constructor.cpp
File metadata and controls
51 lines (38 loc) · 1.05 KB
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
46
47
48
49
50
51
#include<iostream>
using namespace std;
//Deep Copy Constructor
class student{
public:
string name;
float* cgpa; // cgpa pointer, points randomly (it is memory address)
public:
// parameterized constructor
student(string n, float c){
cout<<"Parameterized constructor!"<<endl;
name=n;
cgpa = new float; // points in heap memory
*cgpa = c; // pointer is derefernced and cgpa value stored
}
// copy constructor (deep copy)
student(student &obj){
cout<<"Parameterized constructor!"<<endl;
name=obj.name;
cgpa = new float; // points in heap memory
*cgpa = *obj.cgpa; // pointer is derefernced and cgpa value stored
}
display(){
cout<<"Display function!"<<endl;
cout<<"Name is: "<<name<<endl;
// to find value from pointer, always dereference it through '*'
cout<<"Cgpa is: "<<*cgpa<<endl; //dereferenced to get value
}
};
int main(){
student s1("neha",9.6);
s1.display();
student s2(s1);
*(s2.cgpa) = 5.5; //cgpa is different to s2
s1.display();
s2.display();
return 0;
}