-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnewdelete.cpp
More file actions
78 lines (52 loc) · 1.39 KB
/
newdelete.cpp
File metadata and controls
78 lines (52 loc) · 1.39 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
Author: Xiang Zhao
Date: 4/26/2021
Description:
new delete operator should form a pair
*/
#include <iostream>
using namespace std;
class A {
private:
int data;
int* intPtr;
public:
A() {
data = 1;
intPtr = new int;
*intPtr = 2;
}
~A() {
delete intPtr;
}
int getData() {
return data;
}
int* getIntPtr() {
return intPtr;
}
int getInt() {
return *intPtr;
}
};
int main() {
// new allocates memory for type A and calls A's constructor
// returns object's address
// there are two variables in memory now:
// aPtr and *aPtr i.e. type A pointer and type A object
A* aPtr = new A;
// print variable aPtr's value i.e. object *aPtr's address
cout << "aPtr = " << aPtr << endl;
// dp sth with aPtr
cout << "aPtr->getData() = "<< aPtr->getData() << endl;
cout << "aPtr->getIntPtr() = "<< aPtr->getIntPtr() << endl;
cout << "aPtr->getInt() = "<< aPtr->getInt() << endl;
// delete calls A's destructor and deallocates memory for *aPtr,
// memory for aPtr is intact
delete aPtr;
// print variable aPtr's value
cout << "aPtr = " << aPtr << endl;
// since aPtr points to deallocated memory,
// attempting to use point1 after deletion is a logic error.
//cout << "aPtr->getData() = "<< aPtr->getData() << endl; //Error
}