-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFILE11.cpp
More file actions
49 lines (40 loc) · 1.1 KB
/
FILE11.cpp
File metadata and controls
49 lines (40 loc) · 1.1 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
/*
In C++ the 'new' operator often appears in constructors to allocate memory while initialising an object.
This memory has to be deallocated. This is usually done using the 'delete' operator in a destructor.
In the program below we will use a class that contains a data member which is a string.
We will use a constructor to allocate memory for the string using the 'new' operator.
The destructor of the class will 'delete' the memory space that is allocated to the string data member.
*/
#include <iostream>
#include <cstring>
using namespace std;
class Command
{
private:
char* name;
public:
Command(string s) // Constructor
{
int size = strlen(s.c_str()); // Length of string argument
name = new char[size+1]; // Allocate memory
strcpy(name, s.c_str()); // Copy argument to name
}
void display();
~Command() // Destructor
{
delete[] name;
}
};
void Command::display()
{
cout << name << endl;
cout << "Lenght of the command string: " << strlen(name) << endl;
}
int main()
{
Command first("Start of program");
Command second("Stopping");
first.display();
second.display();
return 0;
}