CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 2012
    Posts
    5

    Question about constructors in an array of objects.

    What the best way to initialize a constructor in an array of objects?

    Usually I declare an array of objects like so:
    Code:
    Car toyota[100];
    Is this the only way I know to initialize a constructor of an array:

    Code:
    for (int i = 0; i < 100; i++)
    {
      toyota[i] = Car(x, y);
    }
    Is this the proper way? Any answer to my question are welcomed.

    Thank You
    Benjamin Betancourt

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Question about constructors in an array of objects.

    Quote Originally Posted by crazyben21 View Post
    What the best way to initialize a constructor in an array of objects?

    Usually I declare an array of objects like so:
    Code:
    Car toyota[100];
    That one line already constructs the objects. Once an array of type T is declared, all of the elements in the array are constructed using the default constructor. So there is no way to construct an array of objects any differently, since declaring automatically constructs objects. Your question then becomes a moot point.
    Code:
    for (int i = 0; i < 100; i++)
    {
      toyota[i] = Car(x, y);
    }
    That code does not construct Car objects on the left side of the equal sign. All you're doing there is assigning to an existing object (toyota[ i ]) the value of a temporary object (Cars(x,y)).
    Is this the proper way?
    If you're asking if this is the "proper" way to assign to an object, then does that way work? Then it is the "proper" way.

    Just to let you know, this does the same thing:
    Code:
    #include <algorithm>
    //...
    std::fill(toyota, toyota + 100, Car(x,y));
    No loop needed.

    Now if you're talking about using a container such as std::vector or std:eque, then this creates a container of Car, and uses Car(x,y) to initialize (using vector as an example).
    Code:
    #include <vector>
    //...
    std::vector<Car> CarVector(100, Car(x,y));
    This basically is just like an array of Car, with each initialized to Car(x,y).

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; October 29th, 2012 at 04:34 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured