array of objects

How would you make an array of a class data type where the class does not have a default constructor, and you need to pass in data? Thanks.

Example:

1
2
3
4
5
6
7
8
9
  #include "MyClass.h"
  #include <array>

  int main()
  {
    array<MyClass, 20> myClassArr = {};
    
    return 0;
  }
Here is a quick example that shows how with minor comments

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <array>

class MyObject
{
    public:
        // No implicit default constructor
        MyObject(int num) : number(num) {}
		
        int getNumber() const { return number; }
		
    private:
        int number;
};

int main() 
{
    // Can use initialization lists and create the objects inside the list.
    std::array<MyObject, 2> objects = { MyObject(1), MyObject(2) };
	
    // Standard C++11 ranged based for loop to print.
    for (auto& i : objects)
        std::cout << i.getNumber() << std::endl;
	
    return 0;
}
Last edited on
C++11 brace initialization is a beast:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <array>

class MyObject
{
    public:
        // More parameters
        MyObject(int num, int foo) : number(num+foo) {}
		
        int getNumber() const { return number; }
    private:
        int number;
};

int main() 
{
    // Braces, braces all the way
    std::array<MyObject, 2> objects {{ {1, 2}, {4, 5} }};
	
    for (auto& i : objects)
        std::cout << i.getNumber() << std::endl;
    return 0;
}
 
std::array<MyObject, 2> objects {{ {1, 2}, {4, 5} }};


@keskiverto
YES! This is how I figured it was done. It's just that I kept getting compiler errors because I was using a single opening and closing brace. Is there a reason why you have to have 2?

@Z e r e o
Thanks. I didn't know you could do it this way.
Topic archived. No new replies allowed.