srccode
srccode

Reputation: 751

Memory allocation to class members in c++

I have one simple question here,

template <class T, MAX_ITEMS>
Class A{
public:
  T buf[MAX_ITEMS];
}

A<class_name, 1000> obj_A;

When I declare obj_A using the last line, does it reserve a space? for sizeof(class_name)*1000 or it would reserve only if I use the new keyword for declaring obj_A?

Upvotes: 0

Views: 106

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 30005

does it reserve a space? for sizeof(class_name)*1000 or it would reserve only if I use the new keyword for declaring obj_A?

Yes, it will allocate enough memory for 1000 elements of that type statically. If your object has static/thread storage duration, then it is likely to work. If your object has automatic storage duration, depending on the type and stack size, it may cause stack overflow.

or it would reserve only if I use the new keyword for declaring obj_A?

If you use the new keyword, it will allocate the memory dynamically (dynamic storage duration). It generally doesn't matter how you create the object; if you manage to create an object of A<class_name, 1000> type successfully, it will surely have room for 1000 objects of type class_name in it.

Learn more about storage durations here.

Upvotes: 1

Related Questions