What's "new"?
Today's article talks about the new, which is an essential operator in C++ for dynamically instantiating an object.
Why do we need new operator?
There's a lot of difference between C's malloc and new. It does more than just allocating memory. It also calls the constructor. Which facilitates to initiate the object.
Believe me, operator new and new operator are completely different!
When we instantiate an object
CTest *pObj = new CTest();
This calls global new operator which performs 2 main tasks
1. Call operator new for allocating memory.
2. Call constructor of the particular object.
We can always overload operator new which performs memory allocation operations. But we cannot change the meaning of the global new operator.
Typical example where we overload operator new will be in case of placement new where we change the actual meaning of operator new by passing address of memory where it has to instantiate the object.
Let's talk about placement new in forth coming articles.
No comments:
Post a Comment