Jump to content
  • Advertisement

Archived

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

supertompa80

Explicit construction of array elements

This topic is 5387 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

Suppose we have a class A with a default constructor and another constructor taking some parameters, say two integers. Now, we want to create an array of A objects and initialize them using the non-default constructor taking two integers as parameters. One way of doing this would be like this,
A** a = new A*[7];
for( int i = 0; i < 7; ++i )
  a[i] = new A( 2,3 );
but I recently stumbled upon another (much cleaner) solution.
A* a = new A[7]( 2,3 );
The shorter version compiles fine with GCC but not at all with MSVC7.1. I haven't tried any other compilers, but is this even valid C++ code? Thanks. [edited by - supertompa80 on September 21, 2003 8:04:18 AM]

Share this post


Link to post
Share on other sites
Advertisement
It''s a GCC extension and not valid C++.

Note that your first example does something completely different from creating an array of A objects - it creates an array of A pointers followed by the A objects themselves.

Share this post


Link to post
Share on other sites
quote:
Original post by spock
It''s a GCC extension and not valid C++.


Ok that''s what I suspected. Thanks!

quote:
Note that your first example does something completely different from creating an array of A objects - it creates an array of A pointers followed by the A objects themselves.


You''re right, of course.

Share this post


Link to post
Share on other sites
To accompish what you want without using an array of pointers, you can look up placement new which will allow you to construct your objects AFTER you allocate the memory for them (or you can write your own overloaded new). If you don''t do that, you can always just use the default constructor and then manipulate the object later.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!