Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You've got a circular reference, so you need to separate B.h. Try something like:</p> <p>B.h:</p> <pre><code>#ifndef B_H_ #define B_H_ // don't include A.h here! class A; class B { private: A&amp; a; public: B(A&amp; a) : a(a) {} void foo(); }; #endif /*B_H_*/ </code></pre> <p>B.cpp:</p> <pre><code>#include "B.h" #include "A.h" void B::foo() { a.bar(); } // now you're ok </code></pre> <p>Edit: explanation for why you need to split it into two files:</p> <p>The class <code>B</code> contains a reference to <code>A</code>, which can be a so-called <em>incomplete</em> type. You can't call any functions on it because the compiler doesn't yet know what the heck <code>A</code> is - it just knows that it's a class of some sort. Once you include A.h (in the .cpp file), then <code>A</code> is a complete type, and you can do whatever you like with it.</p> <p>You can't keep the whole thing in one header file because you'll get a circular reference. You're preventing an infinite loop with your include guards, but you're getting something you don't want. Look at what the compiler ends up with when you compile main.cpp, as you had it before:</p> <pre><code>// #include "A.h" ==&gt; #define A_H_ // #include "B.h" ==&gt; #define B_H_ // #include "A.h" ==&gt; nothing happens! (since A_H_ is already defined) class A; class B { private: A&amp; a; public: B(A&amp; a) : a(a) {} void foo() { a.bar(); } // &lt;-- what the heck is A here? // it's not defined until below }; class A { private: B b; public: A() : b(*this) {} void bar() {} }; int main() { A a; return 0; } </code></pre>
 

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