Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variable construction in C++

Tags:

c++

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?

like image 239
Clark Gaebel Avatar asked Feb 18 '26 22:02

Clark Gaebel


1 Answers

The value of someOtherBaz.bar would 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).

  1. First, baz will be constructed with the default constructor. This will set baz.bar to 3.
  2. Next someOtherBaz will 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. So someOtherBaz.bar will be given the value of 3.
  3. Finally, to construct placeholder, baz.SetBar will be called which will also change the value of baz (but not someOtherBaz since they are independent objects; while you created someOtherBaz based on the value of baz, they are different objects so can change independently).

So, at the end, you'll have:

 baz.bar: 4
 someOtherBaz.bar: 3
 placeholder: 4
like image 159
R Samuel Klatchko Avatar answered Feb 20 '26 12:02

R Samuel Klatchko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!