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){}
5
  • @sshashank124 No. I want to use it in a class and using a constructor. Commented Jan 14, 2020 at 7:55
  • Does this answer your question? Zero-Initialize array member in initialization list Commented Jan 14, 2020 at 7:58
  • I have added a new answer in the duplicate question that specificatlly addresses this one i(initialization to 0 or 0.). Commented Jan 14, 2020 at 8:26
  • @SergeBallesta I have tried the approach you introduced, but it does not work. Commented Jan 14, 2020 at 8: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?) How to Ask to make it a nice question... Commented Jan 14, 2020 at 9:06

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

don't forget #include <cstring>
0

You can write:

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

2 Comments

Tnx. I think it could works
If you have resolved please accept and up my question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.