What does the 'new' operator exactly do?

What does it do? Could someone explain why we need it and how we can use it in other ways? Much appreciated. (LINES: 39-44)

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
#include <iostream>
#include <string>
using namespace std;

class Animal
{
private: 
	string name;

public:
	Animal()
	{
		cout << "Animal Created" << endl;
	}

	Animal(const Animal& other) :name(other.name)
	{
		cout << "Animal created by Copying" << endl;
	}

	~Animal()
	{
		cout << "Destructor Called" << endl;
	}

	void setName(string name)
	{
		this->name = name;
	}

	void speak() const
	{
		cout << "My name is: " << name << endl;
	}

};

int main()
{//---------------------------------
	Animal *pCat1 = new Animal();
	pCat1->setName("Freddy");
	pCat1->speak();
	delete pCat1; //always call delete if you call new, which initializes the destructor
//----------------------------------

	cin.clear();
	cin.sync();
	cin.get();
	return 0;
}
Last edited on
new creates an object on the heap (dynamic memory) and returns a pointer to it. It is used for making objects that need to last beyond their scope.
new, well, creates new object: allocates memory for it in free store and calls constructor of your choice.

We need it to create an object which will persist after current code block.
Or to create object dynamically: when we do not know exact object type we need to create (usually paired with previous point in factories)
Topic archived. No new replies allowed.