Note that there are some explanatory texts on larger screens.

plurals
  1. PO(Simple C++ Concepts) Unexpected output of constructor/destructor calls
    text
    copied!<p>Given this code:</p> <pre><code>#include &lt;iostream&gt; using namespace std; class Foo { public: Foo () { c = 'a'; cout &lt;&lt; "Foo()" &lt;&lt; endl; } Foo (char ch) { c = ch; cout &lt;&lt; "Foo(char)" &lt;&lt; endl; } ~Foo () { cout &lt;&lt; "~Foo()" &lt;&lt; endl; } private: char c; }; class Bar : public Foo { public: Bar () { cout &lt;&lt; "Bar()" &lt;&lt; endl; } Bar (char ch) : Foo(ch) { cout &lt;&lt; "Bar(char)" &lt;&lt; endl; } ~Bar () { cout &lt;&lt; "~Bar()" &lt;&lt; endl; } }; Foo f1; static Bar b1; int main() { Bar b2; { static Foo f2('c'); Foo f3; Bar b3 ('d'); } return 0; } </code></pre> <p><em>(You can just paste this directly into a compiler)</em></p> <p>The <em>first</em> part of my expected sample output is correct:</p> <pre><code>Foo() Foo() Bar() Foo() Bar() Foo(char) Foo() Foo(char) Bar(char) ~Bar() ~Foo ~Foo() ~Bar() ~Foo() ~Foo() </code></pre> <p>But I get the destructor output of the two static objects <code>static Bar b1;</code> and <code>static Foo f2('c');</code> wrong.</p> <p>The correct answer for the last part is:</p> <pre><code>~Bar() ~Foo() ~Foo() </code></pre> <p>I get:</p> <pre><code>~Foo() ~Bar() ~Foo() </code></pre> <p>This is my reasoning:</p> <p>I understand that all local objects are destructed before static objects. Of the two remaining static objects <code>static Bar b1;</code> and <code>static Foo f2('c');</code>, <code>static Foo f2('c');</code> appears <em>last</em>, so it is destructed <em>first</em>, because destructors are called in the reverse order of their creation.</p> <p>But <code>static Foo f2('c');</code> isn't destructed first, <code>static Bar b1;</code> is. Why?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload