-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path46new_delete_this.cpp
More file actions
59 lines (49 loc) · 1.48 KB
/
Copy path46new_delete_this.cpp
File metadata and controls
59 lines (49 loc) · 1.48 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
#include <iostream>
using namespace std;
class A
{
int a;
public:
void setData(int a)
{
this->a = a;
}
void getData()
{
cout << " Value of a is " << a << endl;
}
};
int main()
{
//"new" keyyword / operator for pointers
float *p1 = new float(45.23);
cout << "Value of p1 is " << *(p1) << endl;
int *p2 = new int(7);
cout << "Value of p2 is " << *(p2) << endl;
int *arr = new int[3];
arr[0] = 10;
*(arr + 1) = 20;
arr[2] = 30;
cout << "Value of arr[0] is " << arr[0] << endl;
cout << "Value of arr[1] is " << *(arr + 1) << endl;
cout << "Value of arr[2] is " << arr[2] << endl;
//"delete" keyword / operator
delete arr; // to free the pointer memory
cout << "Value of arr[0] is " << arr[0] << endl;
cout << "Value of arr[1] is " << *(arr + 1) << endl;
cout << "Value of arr[2] is " << arr[2] << endl;
delete[] arr; // to delete enitre block of array
cout << "Value of arr[0] is " << arr[0] << endl;
cout << "Value of arr[1] is " << *(arr + 1) << endl;
cout << "Value of arr[2] is " << arr[2] << endl;
// "this" keyword / pointer
A a;
a.setData(4);
a.getData();
/*
"this" is a keyword which is a pointer which points to the object that invokes the class member
It's other use is to return the object in the member function if there is a need for it
it is required for this since there is no object before the function
*/
return 0;
}