Q:

C++ Static and Dynamic Array Initialization

Let's have a following code:
#include <iostream>

struct TStruct{
  int x;
  int y;
  int * ptr;

  TStruct( void ) : x( 0 ), y( 0 ), ptr( nullptr ) { }
};

int main(){
  TStruct arr[100];
  TStruct * arr2 = new TStruct[200];

  // some code working with these arrays

  for( int i = 0; i < 100; i ++ )
    if( arr[i] . ptr != nullptr )  
      delete [] arr[i] . ptr;
  for( int i = 0; i < 200; i ++ )
    if( arr2[i] . ptr != nullptr )  
      delete [] arr2[i] . ptr;      
  delete [] arr2;
  return 0;
}

How does initialization of both of these arrays - static and dynamic - works? Are they automatically initialized by TStruct constructor or do I have to initialize them manually by looping both of them and setting values for each TStruct member?

A:

The TStruct constructor will be called 300 times with the code you're showing. A hundred times for each element in the array arr, and two hundred times when you allocate memory for arr2.
For the array arr the compiler generates code to call the constructor, and when you use new[] the operator will make sure the constructor is called.

