Aeric Wintershard Aeric Wintershard - 2 months ago 6
C++ Question

c++ Custom type array initialiazion

If I have:

Class SomeClass{
private:
int a;
char* name;
public:
SomeClass(int a = 0, char* n = "---"){
...
}
};

Class OtherClass{
private:
SomeClass anArray[100];
int counter;
...
public:
...
};


How do I initialize the array of type SomeClass? As far as I know, when you have a private member that belongs to a user defined class, to initialize it you should include it in the constructor

OtherClass(...):SomeClass(...){
...
}


However, the contents of the array are left for the user to enter, so they are much too unpredictable, and manually entering default values for each field is obviously out of the question.

Answer

Given that your SomeClass has a default constructor, you don't need to anything: the default constructor will be call for each if the elements. You want to mention it explicitly can use

OtherClass::OtherClass()
    : anArray() {
}

If you want to initialize the sequence of elements with an explicit constructor call with typing it out, you can use a delegating constructor taking a suitably size std::index_sequence<...> and use aggregate initialization of the elements. Here is a complete example of how that would look like:

#include <iterator>
#include <algorithm>
#include <iostream>

struct S {
    int value;
    S(int value): value(value) {}
};
std::ostream& operator<< (std::ostream& out, S const& s) {
    return out << s.value;
}

template <typename S, typename T, std::size_t Size>
constexpr std::size_t static_size(T (S::*)[Size]) {
    return Size;
}

class T {
    S array[100];
    template <std::size_t... I>
    T(std::index_sequence<I...>): array{ S(I)... } {}
public:
    T(): T(std::make_index_sequence<static_size(&T::array)>()) {}
    S const* begin() const { return std::begin(array); }
    S const* end() const   { return std::end(array); }
};

int main()
{
    T t;
    std::copy(t.begin(), t.end(), std::ostream_iterator<S>(std::cout, " "));
}