0

This is what I have. Looks gross.

ABC::ABC(std::string newVar1,int newVar2)
{
    var1=newVar1; 
    var2=newVar2; 
}

Can this be done on the same line? Something like:

ABC::ABC(std::string newVar1,int newVar2):var1,var2
  • 1
    Possible duplicate of [What is this weird colon-member (" : ") syntax in the constructor?](https://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor) – scohe001 Jun 14 '18 at 23:07
  • That's informative and answers the question if you read between the lines, but I'm not sold on full dupe. I'm always annoyed at how one of the most useful features in C++, [the Member Initializer List](http://en.cppreference.com/w/cpp/language/initializer_list), is often ignored or glossed over by education material. – user4581301 Jun 14 '18 at 23:29
  • As to doing it on a single line, sure: you can put all that code on one line. But you won’t like it — it’s too hard to read. – Pete Becker Jun 14 '18 at 23:30

2 Answers2

2

You may do:

ABC::ABC(std::string newVar1, int newVar2) : var1(newVar1), var2(newVar2) {}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

is there a more elegant way of declaring default variables in a constructor?

This would be initialization using the constructor.

You can have member-initialization as follows:

ABC::ABC(std::string newVar1, int newVar2)
   : var1(newVar1)
   , var2(newVar2)
{ }

Can this be done on the same line?

You can format the code above in same line.

Joseph D.
  • 11,804
  • 3
  • 34
  • 67