In this blog post we will discuss some facts of new operator in c++. In c++ new operator allocates memory at runtime. It allocates memory at heap. Allocating memory at runtime is known as dynamic memory allocation. Heap is a free memory of a program and it is also called free store in c++.

Some facts of new operator in c++

  • Memory allocated by new[]  it must be deleted using delete[] operator.
#include<iostream>
using namespace std;

class foo {
public:
	foo() {
		cout << "constr called \n";
	}
	~foo() {
		cout << "destr called \n";
	}
};

int main() {
	// allocate 4 objects
	foo *obj = new foo[5];
	delete[] obj;
	return 0;
}

Note:

In our above program we have allocated memory using new[]. if we would free memory using delete then in this case it would delete entire array but it will call the object destructor only for first object. delete[] frees all array and calls destructor of the each object containing in the array.

  • New allocates memory and call constructor of the class.
  • We should avoid to delete a memory (allocated by new ) using free() function. Let us see below code try to compile and see the output.
#include<iostream>
using namespace std;

class foo {
private:
	char *p;
public:
	foo() {
		p = new char;
		cout << "constr called \n";
	}
	~foo() {
		delete p;
		cout << "destr called \n";
	}
};

int main() {
	// allocate 4 objects
	foo *obj = new foo;
	free(obj);
	return 0;
}

When we will run above program we will see output “constr called “. It means when we delete memory (allocated by new) using free() function ,the destructor does not get called and it leaks memory pointed by character pointer p.



Related Contents to follow