0

In C this can be done easily by doing

int myArray[10] = { 0 }; // all elements 0

(taken from this answer)

My question is, is there a way similar (or same) in C++ which I can use to initialize the array to 0 in the constructor?


EDIT 1

I need to do the above using initialization list.

May be something like

struct aa
{
    int i[10];

    aa() : i {0}{}
};
Community
  • 1
  • 1
Haris
  • 11,989
  • 6
  • 41
  • 67

2 Answers2

0

Here is an example how it can be done

struct A
{
    A() : a{} {}
    enum { N = 10 };
    int a[N];
} a;

Or

struct A
{
    A() : a{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } {}
    enum { N = 10 };
    int a[N];
} a;

for (int x : a.a) std::cout << x << ' ';
std::cout << std::endl;

Another approach is to use an object of type std::array. For example

#include <array>

//...

struct A
{
    A() 
    { 
        a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 
    }
    enum { N = 10 };
    std::array<int, N> a;
} a;

for (int x : a.a) std::cout << x << ' ';
std::cout << std::endl;
Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303
0

Yes. Same syntax applies in C++, although it has a different name (list initialization, or in this case its special case, aggregate initialization).

However, in the member initialization list, you have to use the different syntax: myArray{}. Note that explicitly initializing the first element to 0 is unnecessary, since that is the default.

eerorika
  • 223,800
  • 12
  • 181
  • 301