Archived

This topic is now archived and is closed to further replies.

Initializing array of classes in constructor initialization list

This topic is 5309 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

class ClassOne
{
public
  ClassOne(int Argument) {}
};

class ClassTwo
{
  ClassOne m_MemberClasses[5];
public:
  ClassTwo();
};

ClassTwo::ClassTwo()
: //Problem is here

{
}
Is there a way to call the constructor of each of the elements in the array, or do I need to use pointers?

Share this post


Link to post
Share on other sites
When you declare m_MemberClasses[5], that means that when an instance of ClassTwo is created an array of ClassOne's will be created on the stack and the default constructor will be called on each ClassOne in that array. So, you must define a default constructor for classes you want to put into an array like this.

If you'd like to call anything but the default constructor, the only options are to either use pointers, or like petewood said, use a std::vector (or other similar container) and push_back each element you want in the vector. In either case, you need to create the objects one by one and add them to the array or vector.

[edited by - fizban75 on June 5, 2003 10:19:17 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by fizban75
In either case, you need to create the objects one by one and add them to the array or vector.



not true:


vector<double> myDoubles(5, 6.24);
vector<complex<double> > myComplexes(15, complex<double>(1.2, 5.7));

Share this post


Link to post
Share on other sites
Thanks for the responses. I didn''t think there was a way to do it with a normal array, but I wanted to be sure. I''ll just do it with pointers.

Share this post


Link to post
Share on other sites