* Ian Collins, on 04.05.2011 00:18:
On 05/ 4/11 07:29 AM, Alf P. Steinbach /Usenet wrote:
* asit, on 03.05.2011 20:32:
consider this class
class A
{
int a;
public:
A(int x):a(x)
{
cout<<"Parametrized constructor"<<endl;
}
};
How can I create array of objects ??
I can't add the default constructor and overload the parametrized
constructor.
The simplest solution is to use std::vector, from the<vector> header.
E.g.
std::vector<A> myArray;
myArray.push_back( A( 1 ) );
//...
And that's what you should be doing anyway, as a beginner. Don't mess around
with raw arrays. For that matter, don't add assembly language stubs either. ;-)
In this case, using a temporary array as a helper would be fine:
A tmp[] = { 1,2,3,4 };
std::vector<A> a(tmp, tmp+(sizeof(tmp)/sizeof(A)) );
I disagree.
Even an experienced programmer like yourself gets it, well not technically wrong
but pretty imperfect. :-(
If done, it would better look like this:
int const tmp[] = { 1,2,3,4 };
std::vector<A> a(tmp, tmp+(sizeof(tmp)/sizeof(*tmp)) );