Home > OS >  how do you assign an array for a default constructor?
how do you assign an array for a default constructor?

Time:05-26

I am very new to c and I'm having issues with making a class. So i have this pad class and it has double inputs of the x and y coordinates for the sides of the pad. to elaborate, say you had a pad of 2cmx2cm it would have pad({0.0,2.0},{0.0,2.0}). I wanted to set the default constructor to be a pad of 0x0.

class pad {
public:

    double xcor[2]={0,0};
    double ycor[2]={0,0};
    double charge=0;
   pad() =default;// put this for now to work on code that works with the pad object

    pad(double xcord[] , double ycord[] ) {
        for(int i =0;i<2;i  ){
            xcor[i]= xcord[i];
            ycor[i]= ycord[i];
        }
    };

CodePudding user response:

What you did in lines such as:

double xcor[2]={0,0};

is called default member initializer. As you can see in the link, it is setting the value of the data member before running the body of the constructor. In your case it will initialize the xcor, ycor etc. before invoking the default constructor which will not modify them. You will be left with the values as you wanted.

Side notes:

  1. If you use a member initializer list, it has precedence over the default member initializer:

If a non-static data member has a default member initializer and also appears in a member initializer list, then the member initializer is used and the default member initializer is ignored

  1. I agree with the advice in the comments above to use std::array instead of a C style array.

CodePudding user response:

You are making things more complex than they need to. pad is an aggregate type and you can simply use aggregate initialization:

class pad {
public:

    double xcor[2]={0,0};
    double ycor[2]={0,0};
    double charge=0;
};

pad pad0{};
pad pad1{{1,2}};
pad pad2{{1,2}, {3,4}};
pad pad3{{1,2}, {3,4}, 23};

But if you do want to have more complex constructors then do use std::array instead of C-style arrays as they follow value semantics and passing them around as arguments to functions comes naturally. Passing C-sytle arrays has a horrible syntax and is never safe from accidental errors.

  •  Tags:  
  • c
  • Related