Dave Hylands (DHylands@creo.com)
Fri, 24 Sep 1999 14:05:56 -0700
I'm not that familiar with the GNU compiler yet, but in "standard" C++ you
can't do this in a simple one line fashion.
You have a number of options:
1 - Create the array using the default constructor, and then go and
re-initialize the elements afterwards. This has the potential downside that
the object gets constructed twice, once using the default constructor which
then gets overwritten.
2 - Create a derived class whose default constructor calls an alternate
constructor in the base class:
class My_24_Point: public Point { public: My_24_Point() : Point( 2,
4 ) {} };
declare your variable like:
My_24_Point[ 20 ];
Since it's derived from Point, you can do everything on a My_24_Point
that you can do on a Point.
3 - Use the placement new operator. This is a variant of new where you
provide the memory and initialize the object into the already allocated
memory:
Point *ptArray = reinterpret_cast< Point * >( new char[ sizeof(
Point ) * numElems ]);
for ( int i = 0; i < numElems; i++ )
{
new( ptArray[ i ] )Point( 2, 4 );
}
You then destruct the elements using:
for ( int i = 0; i < numElems; i++ )
{
ptArray[ i ].~Point();
}
I believe that a placement delete is being added to the language
specification,
but until it's added, you have to manually destruct the objects as
shown above.
You can then wrap all of this up into a PointArray class so
everything gets constructed/destructed automagically.
-- Dave Hylands Email: DHylands@creo.com 3700 Gilmore Way Principal Software Developer Tel: (604) 451-2700 x2329 Burnaby B.C. Creo Products Inc. Fax: (604) 437-9891 Canada V5G 4M1
This archive was generated by hypermail 2.0b3 on Mon 15 Nov 1999 - 09:39:28