title: C++ volatile object, nonvolatile member
body: <p>As in the question:
  let's say I have a small piece of code like this:</p>
  
  <pre><code>  #include &lt;iostream&gt;
    using namespace std;
  
    struct foo {
        int a; 
        foo() : a(12) {};
    };  
  
    int
    main()
    {
        volatile foo x;
        return 0;
    }   
  </code></pre>
  
  <p>compiled with <code>g++ -g -O2</code> it turns out, that <code>x</code> initialization is optimized away.</p>
  
  <p>That one however:</p>
  
  <pre><code>  #include &lt;iostream&gt;
    using namespace std;
  
    struct foo {
        volatile int a; 
        foo() : a(12) {};
    };  
  
    int
    main()
    {
        volatile foo x;
        return 0;
    }   
  </code></pre>
  
  <p>calls the constructor. </p>
  
  <p>If I try to use the variables inside the code, (ie. <code>cout &lt;&lt; foo.a &lt;&lt; endl;</code>) the assembly output is equivalent in both cases. </p>
  
  <p>Do I get the following right, that:</p>
  
  <p>In the first case, there's no access to the struct at all, so it gets optimized away completely.</p>
  
  <p>In the second one, struct's field is indicated as the one possible to change also during the construction and for that reason foo() is called no matter what.</p>
  
  <p>Added:
  I've tried fiddling with the above code:
  calling things like <code>while(foo.a--);</code> works as expected, it actually happens instead of being deleted/replaced by result during optimization, thus it seems the volatile is actually inherited, yet the ctor behaves in this strange (or at least unexpected at first) way.</p>
  
  <p>EDIT number 2:</p>
  
  <p>I checked it with clang and MSVC and it behaves the same way as in gcc.</p>