3

I need to initialize an array of objects of a parametrized constructor . How can i do it in best possible way ?

   # include<iostream>
   # include<conio.h>
   # include<stdio.h>

   using namespace std;

   class A
   {
    public:
    int a;       
    A();
    A(int x)
    {
     a=x;
    }      
   };
   int main()
   {
    A *a1,a2(1);
    a1 = (A*)malloc(sizeof(A)*10); // equivalent to A[10]. 
    for(int i=0;i<10;i++) a1[i]=a2; // Initialization is important in any program.
    for(int i=0;i<10;i++) cout<<a1[i].a; 
    getch(); 
    return 0;   
   }

This does work but is there some other way better than this ?

Invictus
  • 4,028
  • 10
  • 50
  • 80

3 Answers3

4

The C++ way would be to use a std::vector.

std::vector<A>   a1(10, 1);

creates 10 A's initialized by 1.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • This requires A(int) to be not explicit I think ? – Joel Falcou Feb 14 '12 at 18:24
  • Probably, but it isn't in the example. – Bo Persson Feb 14 '12 at 18:25
  • sure, wanted to be sure as I wanted to answer the very same thing but thought something was maybe amiss :) – Joel Falcou Feb 14 '12 at 18:27
  • @BoPersson Its not explicit in my case . However how does the destruction of these object take place ? Is it just by calling clear function of vector ? – Invictus Feb 14 '12 at 18:35
  • 1
    The vector will destroy itself when it goes out of scope (at the end of main). Or you can call clear if you want to empty it earlier. – Bo Persson Feb 14 '12 at 18:38
  • @BoPersson In the above program if i declare a destructor i get a compilation error [Linker error] undefined reference to `A::~A()'but without destructor code works fine – Invictus Feb 14 '12 at 18:49
  • 1
    @Ritesh - You cannot just declare a destructor, you have to define it as well. But the above class doesn't need one. – Bo Persson Feb 14 '12 at 18:54
  • A helpful clarification on this answer: vector will construct one object of type A based on an implicit conversion from int (because the constructor was not marked 'explicit' (as mentioned before). Then vector will use the copy constructor to construct 10 copies of this object. If your class does not have a valid (default or user-defined) copy constructor, this method won't work. – jfritz42 Nov 13 '14 at 23:02
0

This is solved using std::vector constructor taking size and base element :

A a2(1);
std::vector<A> tab(10, a2);
Joel Falcou
  • 6,247
  • 1
  • 17
  • 34
-1

Note that malloc does not construct objects, and so calling a1[i]=a2 is bad form. It probably seems to work fine since they are POD-ish objects, but this is not the proper way to do C++. It is undefined behavior, which is completely unpredictable. It may work ten thousand times in a row, and then erase your bank account. You should use new instead, which also constructs. Or better yet, use a vector, like the other answers suggest. Also, be sure that the default constructor initializes the data, and initialization will be less of a worry.

If you really must use malloc, the "correct way" to initialize is this:

std::uninitialized_copy(a1, a1+10, a2); //constructs and assigns

which is roughly equivalent to:

{
    int i=0;
    try {
        for(i=0; i<10; ++i)
           new(a1+i)A(a2); //constructs and initializes in the buffer
    } catch(...) { 
        try {
            for(; i>=0; --i)
               (a1+i)->~A(); //destroy if an error occured
        } catch(...) { 
            std::terminate();
        }
        throw;
    }
}
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158