0

When creating struct or classes, usually attributes don't have a specific value at all, and when they call the constructor, they assign the values that they want.

struct Point{
    int x;
    int y;
}

Point myPoint = {0,0};

However when is appropriate the following case?

struct Point{
    int x = 0;
    int y = 0;
}

I'm in some sort of way trying to specify the default values of each attribute, then change it when necessary

Point center; //This is (0,0) by default

Point myPoint;
myPoint.x = 7;
myPoint.y = 14;

Also, are these approaches valid when working with classes?

David Meléndez
  • 389
  • 5
  • 15
  • 3
    Declaring default values doesn't prevent you from constructing with different values if needed, eg: `struct Point { int x = 0; int y = 0; }; Point center; Point myPoint{7,14};` – Remy Lebeau Oct 06 '20 at 21:25
  • Okay, then which one is the right way to do it, or are both of them correct? – David Meléndez Oct 06 '20 at 21:26
  • 1
    They are both correct. It comes down to which context(s) you decide to use them in. – Remy Lebeau Oct 06 '20 at 21:27
  • 1
    related/dupe: https://stackoverflow.com/questions/36600187/whats-the-differences-between-member-initializer-list-and-default-member-initia – NathanOliver Oct 06 '20 at 21:33
  • "However when is appropriate the following case?" If you are starting to see that you want to initialize your data attributes, I recommend a ctor function with an initialization list. – 2785528 Oct 06 '20 at 23:03

1 Answers1

2

However when is appropriate the following case? [example with default member initialisers]

Depends on what standard version you use, and what you need from the class:

  • It is not appropriate prior to C++11 because that is when default member initialisers were introduced to the language.
  • It is not appropriate prior to C++14 if you need the class to be an aggregate, because default member initialisers would disqualify the class from being an aggregate prior to that version.

Otherwise it is appropriate to provide default member initialisers assuming reasonable defaults exist.

Also, are these approaches valid when working with classes?

Yes; both are valid.

eerorika
  • 232,697
  • 12
  • 197
  • 326