-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic_memory.cpp
More file actions
59 lines (46 loc) · 1.11 KB
/
dynamic_memory.cpp
File metadata and controls
59 lines (46 loc) · 1.11 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>
#include <memory>
#include <stdlib.h>
using namespace std;
const int NumElements = 10;
const int dataLimit = 30;
class Roll
{
public:
Roll ()
{
}
void startRolling ()
{
cout << "started rolling!!" << endl;
}
~Roll ()
{
}
};
int main ()
{
int *a = new int [NumElements]; // Allocating an array
double &d = *new (nothrow) double(5.2); // Allocating an object and assigning it to a reference
string *illustration = NULL;
try
{
illustration = new string ("Illustrating allocation"); // Allocating a single object
}
catch (bad_alloc &ba)
{
cerr << "bad_alloc caught: " << ba.what() << endl;
}
// Initialize random seed
srand(time(NULL));
for (int i = 0; i < NumElements; i++) {
a[i] = rand () % dataLimit;
}
cout << "a[2] - " << a[2] << "\nillustration string - " << illustration << "\ndouble val - " << d << endl;
// delete [] a[2] // deleting the content of an array
delete [] a; // deleting an array
delete &d; // deleting a reference
Roll *pRoll = new Roll (); // Create a class instance dynamically
pRoll->startRolling ();
delete pRoll; // release the memory
}