Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In the array of objects, constructor is called many times but operatror new[] only once , why?

Tags:

c++

When object is created in the heap, it (new) does two things.

1: calls operator new

2: calls constructor to initialize the obejct.

I am trying to create array of objects, for example 4 objects , so it calls constructor and destructor 4 times that makes sense but it only calls one time operator new[] ?? why? Following is the code that i am trying to run.

#include <iostream>
using namespace std;
class test
{
    public:
       static void *operator new[] (size_t size)
       {
           cout<<"operaotor new called"<<endl;
           return ::operator new[](size);
       }

       test()
       {
          cout<<"constructor called"<<endl;
       }
       ~test()
       {
          cout<<"destructor called"<<endl;
       }
};

int main()
{

     test *k = new test[4];
     delete []k;
}
like image 221
Alok Avatar asked Oct 16 '25 11:10

Alok


1 Answers

operator new[] is only there to allocate the necessary space, nothing else. Of course, it will do so only once, as anything else would be nonsens and wouldn't get a contiguous buffer. The size parameter you're getting, in the case of new test[4], should be 4 * sizeof(test).

like image 159
Xeo Avatar answered Oct 19 '25 00:10

Xeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!