1

Suppose we have a class like the following one:

class myprogram {
public:
myprogram ();
private:
double aa,bb,cc;};
myprogram::myprogram():aa(0.0),bb(0.0),cc(0.0){}

As you can see we can initialize our private members' aa, bb, cc using the myprogram() constructor.

Now, suppose I have a large private array G_[2000]. how I could initialize all the values of this array equal to 0 using a constructor.

class myprogram {
public:
myprogram ();
private:
double aa,bb,cc;
double G_[2000];};
myprogram::myprogram():aa(0.0),bb(0.0),cc(0.0){}
  • @sshashank124 No. I want to use it in a class and using a constructor. – Seyyed Kazem Razavi Jan 14 '20 at 07:55
  • Does this answer your question? [Zero-Initialize array member in initialization list](https://stackoverflow.com/q/27382036/580083) – Daniel Langr Jan 14 '20 at 07:58
  • I have added a new [answer](https://stackoverflow.com/a/59729934/3545273) in the duplicate question that specificatlly addresses this one i(initialization to 0 or 0.). – Serge Ballesta Jan 14 '20 at 08:26
  • @SergeBallesta I have tried the approach you introduced, but it does not work. – Seyyed Kazem Razavi Jan 14 '20 at 08:41
  • *it does not work* just means nothing. You'd better ask a new question refering this one and my answer if it helps and explaining what you have tried, the expected result and the actual result. Be sure to read (again?) [ask] to make it a nice question... – Serge Ballesta Jan 14 '20 at 09:06

2 Answers2

1

Use std::memset function in constructor's body.

For example,

myprogram::myprogram()
     : aa{0.0}, bb{0.0}, cc{0.0}
{
    std::memset(G_, 0, 2000 * sizeof(double));
}

However, if you use braces {} in your initializer list, it will set default-initialize object (In case of array, it will fill it by zeroes).

Ladence
  • 244
  • 2
  • 9
0

You can write:

    myprogram::myprogram()
    {
          for(int i=0;i<2000;i++)
             G_[i]=0;
    }