Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Writing the Constructor for the Array for Objects

  1. Oct 5, 2005 #1
    consider the program
    Class A
    {
    int a;
    public:
    A(int m = 0)
    {
    a = m;
    }
    }

    int main()
    {
    int i = 0;
    /* Intansiate/Initilize Object with the Constructor */
    A Object(0);
    /* Here is the Problem */
    /* Create the 32 Objects of Class A */
    A nObjects[32]; /* ... How to instantiate here for the array of objects?? */
    }

    Now if i want to initialize the nObjects.a = i during the constructor call;
    How do i achieve that?
    Here i get a compiler error stating no constructor match found for nObjects.
     
  2. jcsd
  3. Oct 5, 2005 #2

    saltydog

    User Avatar
    Science Advisor
    Homework Helper



    Well that's interesting. I dont' think you can. When the compiler creates the array of 32 A items, it calls the constructor 32 times. Pretty sure anyway. Don't think you can link into this calling phase and pass dynamic data to the constructor while that's being done. Can always just initialize it after the array is instantiated. Not as elegant I know. Could be wrong though. I'd bet only a dollar I'm right.
     
  4. Oct 5, 2005 #3

    dduardo

    User Avatar
    Staff Emeritus

    You could do something like this:

    A nObjects[32] = {1,2,3,4,5,6,7,8,....,32};
     
  5. Oct 6, 2005 #4

    saltydog

    User Avatar
    Science Advisor
    Homework Helper

    Thanks. :blushing:
     
  6. Oct 6, 2005 #5
    dduardo i always forget that method could you....for large parameter list
    like constr(char*,int) do you just do

    ={ "",1, "",2,"",3 ...};
     
  7. Oct 6, 2005 #6

    saltydog

    User Avatar
    Science Advisor
    Homework Helper

    Dduardo . . . I knew it just as good as you at one time. Suppose that don't help me now though. And I really like using a debugger. That's especially nice with C++ so you can see all the calls, you know for polymorphism.

    Anyway . . . good for you Dduardo. :smile:
     
    Last edited: Oct 6, 2005
  8. Oct 25, 2005 #7
    I still dont find to have got a sufficing solution. Its really bugging me out.
    For the fact that I can achieve the same in Java because of the new () for each objects, that actually instantiates the individual objects.
    Here in C++ i dont thing that i have any other options, other than initializing each of the objects in a loop, after instantiating(creating) them with the constructor calls.
     
  9. Oct 25, 2005 #8
    The new operator exists in C++. The difference with Java is that Java declares only references (pointers) to objects which are then created with the new operator and linked with the pointer automatically by Java. In C++ you can do the same yourself: declare an array of pointers and then create the objects with the new operator.
    A* objects[ i ];
    and initialize them in a for loop.
    objects[ i ] = new A( value );
     
  10. Oct 25, 2005 #9

    dpm

    User Avatar

    There's two solutions: either use the solution that ramollari suggests and use new, or provide a default constructor (a constructor that takes zero arguments) and provide a seperate method called "initialise" or somesuch which can be called on each element of the array.

    Please be careful when using new, however, especially if you are used to using Java. Any new'd memory must be deleted, and if you declare an array using new [], you must also use delete []. Failure to do this will result in a memory leak and a possible loss of system stability.

    Furthermore, never mix new and free and malloc and delete.

    Example:

    Code (Text):

    int main()
    {
        A* array = new A[32];
        for(int i = 0; i < 32; ++i)
            array[i] = new A(5);
        delete [] array;
        return 0;
    }
     
     
  11. Oct 25, 2005 #10

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    First off, I'm puzzled that your code, as written, doesn't compile, since you do give a default constructor for A.


    Another option, though a little trickier, is to allocate raw memory, and instantiate your A objects directly in that memory.

    E.G. something like:

    Code (Text):

    unsigned char *buffer = new unsigned char[n * sizeof(A)];
    A *array = (A*) buffer;

    for(int i = 0; i < n; ++i) {
      // Create an object -here- without allocating
      new( (void*)(array + i) ) A(i);
    }

    // Do stuff

    for(int i = 0; i < n; ++i) {
      // Destroy this object without deallocating
      array[i].~A();
    }
    delete[] buffer;
     
    Incidentally, buffer could have been statically allocated too, instead of dynamically allocated as I did.


    If you're using the STL, you should also be able to do something like this:

    Code (Text):

    std::vector<int> init(32);
    for(size_t i = 0; i < 32; ++i) init[i] = i;
    std::vector<A> array(init.begin(), init.end());
     
    but, of course, this only works when you just want to use a one-parameter implicit constructor. A good implementation of the STL will not use the default constructor for A when compiling the above code.
     
    Last edited: Oct 25, 2005
  12. Oct 25, 2005 #11

    dpm

    User Avatar

    I don't think the guy needs to worry about memory pooling just yet :biggrin:
     
  13. Oct 25, 2005 #12

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Probably not. But it's fun to know that you can do it, even if you don't intend to try to do it. :smile: And there's always the chance he genuinely needs to do something like this, and double indirection (array of pointers to objects) is too slow or fragmented for his needs.
     
  14. Oct 26, 2005 #13
    1. The Code was not compiling, since i had a constructor that takes 1 parameter, like this
    A(int m )
    {
    a = m;
    }
    So as to make the code compilable,I modified the above constructor to take 1 or Zero Argumnets.

    2. I'm not really intersted in explicitly initializing the objects after having created/ initilized(by Constructors).

    What I really intend is to use the constructors, to intialize the objects during the time of their creation to a particular value, that can be passed as an argument to the constructor.

    Since i needed the above count to work only for the Local objects that are created in some function, I had implemted the required behavior in a different fashion. As shown below

    static int Loacal_Objects_Counter = 0;
    Class A
    {
    int a;
    public:
    A()
    {
    a = Loacal_Objects_Counter ;
    }
    A(int m)
    {
    a = m ;
    }

    };
    int func()
    {
    /* Store the Objects_Counter Value */
    int Currnet_Counter = Local_Objects_Counter;

    /* Reset the Local_Objects_Counter */
    Local_Objects_Counter = 0;

    /* Calling the Zero Arg Constructor :: Thus having initailized the objects during the construction as desired */
    A Objects[32] ;
    /* Do the Rest */
    ...........
    /* Reset the Static Counter Back to its initial value. */
    Local_Objects_Counter = Currnet_Counter;
    }

    Though i could achieve, what i intended, i was not satisfied in using the file/class specific static variable,
    And also the overhead in each of the functions, to store and restore the counter varaible.
    I m in search of a better alternative.
     
  15. Oct 26, 2005 #14

    dpm

    User Avatar

    I have no idea what you are trying to do. I read your explanation, read your code and I'm still none the wiser. Why have you introduced a static variable? Why not simply use new instead of allocating your objects on the stack?
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?