On Jul 1, 11:05 am, Peskov Dmitry <vamsi.kom...@gmail.comwrote:
On Jul 1, 3:48 am, Ivan Novick <i...@novickmail.comwrote:
On Jun 30, 10:03 am, Peskov Dmitry <vamsi.kom...@gmail.comwrote:
class simple_class
{
int data;
public:
simple_class() {data=10;};
simple_class(int val) : data(val){}
};
int main()
{
simple_class obj1(10); // Initializing a single object through
single parameter constructor
return 0;
}
How to initialize the values of array of simple_class objects during
declaration through the single paramter constructor?
1 method i know is
simple_class obj_array[]={5,6,10};
However, I would like to know if there is any alternative way so that
i can initialize things while declaring an array of objects ?
What is wrong with the code you showed? That is perfectly valid way
to initialize objects in an arary:
simple_class obj_array[3] = {5,6,10};
Ivan Novickhttp://www.mycppquiz.com
I am looking for any alternative way of declaring for arrays in
general something like...
simple_class obj_array[10](100); // I know this syntax is wrong.
will intialize all the 10 objects to 100 using a single parameter . I
need a similar syntax.
Its time you start digging into STL containers, both sequenced and
associative containers.
Look at std::vector in this case.
Beware if you do - you'll rarely ever use an array again.
#include <iostream>
#include <vector>
class simple
{
int data;
public:
simple() : data(0) { }
simple(int val) : data(val) { }
};
int main()
{
std::vector< simple container(1000, 10);
std::cout << container.size() << std::endl;
}
/*
1000
*/
And your container now has 1000 elements all with the precious member
initialized to 10
That vector is dynamic (it can grow / resize).
If i was to step through all the reasons why a vector is a much better
choice than an array, this post would be humongous. Array means more
code, more work. The Vector is a workhorse, simple, and quite
versatile.