1

I have a class called MyClass , with a print given when the constructor or distractor is called. I am trying to allocate memory from new operator. I have some question on the output of below code.

<code>
#include...
class MyClass
{
    public:
    MyClass()
    {
        cout << "MyClass Object Created \n";
    }

    ~MyClass()
    {
        cout << "MyClass Object Deleted\n+";
    }
};
int main(int argc, const char * argv[])
{
  int size = 0; // if the size is zero
  std::cout << "Hello, World!\n";
  MyClass *mclass = NULL;
  cout << "before allocating the memory :" <<  mclass << endl;
  mclass = new MyClass[size](); //object will not be constructed.
  cout << "after allocating the memory :"<<  mclass << endl;
  delete [] mclass;
  cout << "after deallocating the memory :"<<  mclass << endl;
  return 0;
}
</code>

Questions - 1. if array size is 1, 2,... any int value constructor is called but when the array size is 0 constructor is not called though memory is allocated

  1. according to new operator if the memory is allocated constructor should be called.
S. Jaiswal
  • 19
  • 1
  • If you're allocating 0 elements, there should be 0 calls to the constructor (obviously). The memory you're getting doesn't have to contain an initialized object. – Clearer Apr 15 '18 at 11:31
  • Instead of dynamic allocation of raw array, consider using `std::vector`. It takes care of the memory management for you, and has much useful functionality. – Cheers and hth. - Alf Apr 15 '18 at 11:33

1 Answers1

2

With array size zero there are no array items to construct.

It's that simple.

You get a unique address though, and that means at least one byte has been allocated, which must be freed as usual.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331