0

Is it correct to use the member of a struct that we are initializing? My compiler does not complain with the following code:

#include <iostream>

struct Foo {
  int a, b;
};

int main() {
    Foo foo {34, foo.a + 2}; // I'm using `foo.a` during the `foo` initialization
    std::cout << foo.a << "   " << foo.b << std::endl;
    return 0;
}

// Prints "34   36"

But it seems weird since foo is not declared yet when I use it inside the braces.

Jojolatino
  • 696
  • 5
  • 11
  • 2
    On a side note, it is bad design IMO. If `b` depends on `a`, `Foo`'s constructor should take care of it. – CinCout Dec 22 '21 at 16:49

1 Answers1

0

This is fine and valid as long as you keep a declared before b as you're doing right now.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122