Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your're instantiating an object <code>y2</code> of incomplete type <code>yyy</code> here:</p> <pre><code>{ a = 20; yyy y2; y2.show(); } </code></pre> <p>Move the implementation of constructor below the definition of <code>yyy</code> class:</p> <pre><code>class yyy; class xxx { private: int a; public: xxx(); void show() { cout &lt;&lt; "a=" &lt;&lt; a &lt;&lt; endl; } friend class yyy; }; class yyy { private: int b; public: yyy() { b = 10; } void show() { cout &lt;&lt; "b=" &lt;&lt; b &lt;&lt; endl; } }; xxx::xxx() { a = 20; yyy y2; y2.show(); } // No error </code></pre> <p>As a result, at this point <code>yyy</code> is already defined, and you can instantiate <code>y2</code>.</p> <p>To give you a logical explanation, why your variant didn't work: when you instantiate an object with <strong>automatic storage duration</strong> (on stack) like <code>yyy y2;</code>, compiler has to know at <strong>compile-time</strong> how much memory it should reserve for <code>y2</code>. Since the <code>yyy</code> type is incomplete (was only forward declared at the point of instantiation), the compiler is lost and reports an error.</p> <p><strong>NOTE:</strong> The best practice, is of course to separate definition of the class and its implementation by moving definition to header file (<code>.hpp</code>) and implementation to source file (<code>.cpp</code>). Don't forget to include headers properly. I don't feel like giving you an example here because it's very basic stuff and should be covered by any C++ book or a tutorial.</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