* Paul:
Often I come across situatation where I need to create array of
objects with parameterized constructors, there are alternative ways to
do this, but why can't it be a standard feature in C++.
some thing like this...
claas A
{
public:
A(){}
A(int v):_x(v),_y(v){}
A(int v, int w):_x(v),_y(w){}
private:
int _x;
int _y;
};
int main()
{
A *p1 = new A[3](5); //all objects have same value
A *p2 = new A[3]((5),(5,10),(20)); //objects have different values
return 0;
}
Is there any reason for not having some thing like this, or just
because of its complex to implement???
There's no compelling reason to complicate the language since you control
the A class.
One case (i) is when you know the values at compile time, then you can
simply use an ordinary array initializer:
A arr[] = { A(5), A(5,10), A(20) };
A second case (ii) is the first in your program where all objects have the
same value, which is what std::vector provides you with:
std::vector<A> arr( 3, A(5) );
Of course that solution (ii.a) means that A-objects must be copyable, but
presumably if they're to be in an array they are. If not and the array size
is fixed at compile time then you can (ii.b) employ the case (i) solution,
although it's a bit tedious. If A-objects are non-copyable and the array
size isn't known at compile time, then the best you can do in practice,
except implementing a placement-new based thing à la std::vector,
which is too horrible to complement, is (ii.c) to use an array or vector of
(possibly smart) pointers.
A third case (iii) is when you don't know the values at compile time and
don't know the array size at compile time. Then if A-objects are copyable
you can use std::vector, e.g. by (iii.a) giving it a "smart iterator". This
assumes that an object carrying the constructor arguments can be "light",
whereas the A-object constructed from those arguments will be "heavy":
#include <iostream>
#include <vector>
class A
{
public:
class Arg
{
public:
Arg(): _v( 0 ), _w( 0 ) {}
Arg( int v ): _v( v ), _w( v ) {}
Arg( int v, int w ): _v( v ), _w( w ) {}
int v() const { return _v; }
int w() const { return _w; }
private:
int _v, _w;
};
A( Arg const& data = Arg() ): _x( data.v() ), _y( data.w() ) {}
int x() const { return _x; }
int y() const { return _y; }
private:
int _x, _y;
};
int main()
{
std::vector<A::Arg> args;
// The following is assumed to be some dynamic thing.
args.push_back( A::Arg( 5 ) );
args.push_back( A::Arg( 5, 10 ) );
args.push_back( A::Arg( 20 ) );
std::vector<A> arr( args.begin(), args.end() );
for( size_t i = 0; i < arr.size(); ++i )
{
std::cout << "( " << arr
.x() << ", " << arr.y() << " )\n";
}
}
If A-objects are non-copyable then we're into case (iii.b), which I'm too
lazy to write anything about right here.