-
Notifications
You must be signed in to change notification settings - Fork 14
/
memoryDeallocationusingDestructor.cpp
65 lines (38 loc) · 1.1 KB
/
memoryDeallocationusingDestructor.cpp
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
//destructor example
#include<iostream>
#include<string>
using namespace std;
class human
{
public:
human(int iage,string iname) { //constructor
//pointers to a memory location/dynamic memory allocation
name = new string;
age = new int;
*age = iage; //assigning value to the pointers
*name= iname;
cout<<"Default Constructor is called"<<endl;
}
void introduce()
{
//accessing value of pointer using value operator *
cout<<"Hello I am" <<" " << *name << " "<<"and my age is" << *age<<endl;
}
~ human() { //destructor
delete name; //deallocating memory allocated to the class variables
delete age;
cout<<"All resources released"<<endl;
}
private:
int *age;
string *name;
};
main() {
human *obj; //pointer to object of type human
obj = new human(20,"Anish"); //memory block allocated to the object in the HEAP memory
//destructor not called as object is not deleted
obj->introduce();
//deallocating the memory allocated to the object
delete obj;
return 0;
}