How do compilers know how to correctly handle this code?
struct Foo
{
int bar;
Foo()
{
bar = 3;
}
Foo& operator=(const Foo& other)
{
bar = other.bar;
return *this;
}
int SetBar(int newBar)
{
return bar = newBar;
}
};
static Foo baz;
static Foo someOtherBaz = baz;
static int placeholder = baz.SetBar(4);
What would the final value of someOtherBaz.bar be?
The value of
someOtherBaz.barwould be 3.Static objects within a translation unit are constructed in the order they appear within the TU (note, there is no defined order of static object in different translation units).
bazwill be constructed with the default constructor. This will setbaz.barto 3.someOtherBazwill be constructed via the copy constructor. Since no copy constructor was defined, a default copy constructor will be used which will just copy each field. SosomeOtherBaz.barwill be given the value of 3.placeholder,baz.SetBarwill be called which will also change the value ofbaz(but notsomeOtherBazsince they are independent objects; while you createdsomeOtherBazbased on the value ofbaz, they are different objects so can change independently).So, at the end, you’ll have: