C++ Dynamic array object


In C++ an array of object created dynamically is known as dynamic array object.The syntax of declaring dynamic array object is same as the syntax of the array for the built-in data type.The object created is an array so the compiler does the initialization of the object one by one.Thus if the storage allocated is for five objects then the constructor is call five times.This pattern is also followed when destroying the object,for each object in the array the destructor is called one by one.The program below shows the constructor and destructor call and how to initialize each object when an array of object is created dynamically.

class C
{
 int i ;
 string s;

public:
 C(int ii=0 , string ss=” ” ) :i(ii) , s(ss) { cout<<“Constructor\n”; }

 int int_content() const { return i; }

 string string_content( ) const { return s;}

 ~C( ) { cout<<“Destructor\n”; }
};

int main( )
{
C *v=new C[3]{ C(3 , “happy”) , C(98 , “Sad”) , C(123 , “Lonley”) };

cout<<v[0].int_content()<<endl
 <<v[1].string_content()<<endl
 <<v[2].string_content()<<endl
 <<v[2].int_content()<<endl;

delete []v; //Do not forget!

cin.get( ) ;
return 0 ;
}

You might have noticed in the program but just reminding in case you haven’t,there is a square bracket in front of the memory pointer while deleting the storage.Do not forget to add the square bracket because including that will delete the whole storage,if it is not included only the first array element is deleted and there will be a memory leakage.





Introduction to smart pointers(C++11 features)

C++ new function not only allocates dynamic storage but also calls constructor which performs the initialization of the object.Allocating a dynamic storage in C++ way thus provides no limitation.However, deleting a dynamic storage can sometime be overlooked by the programmer.Consider the function below.

int* new_call(size_t t)
{
return new int(t) ;
}

The function returns a pointer to dynamic storage of int type and the responsibility of deleting that storage falls in the hand of the function caller.If the caller fails to delete the storage there will be memory leakage.This kind of limitation can be solved by using smart pointers where the storage is deleted automatically after it goes out of scope and the function caller need not worry about deleting the storage.Such property of smart pointers make them an ideal choice to work with when our program involve manipulation of dynamic storage.The basic and in-depth discussion of each smart pointers is shown in other posts.

Link :C++11 smart pointers


Related Link

->Dynamically allocating memory in C++ with new and delete operators.
 
->New,delete operators and class object.