Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can I not define a member function in a class if that function is to be linked from another translation unit?
    primarykey
    data
    text
    <p>I am a bit of a newbie in C++, but I just stumbled on the following. </p> <p>If I have these files:</p> <p>myclass.hpp:</p> <pre><code>class myclass { public: myclass(); void barf(); }; </code></pre> <p>mymain.cpp:</p> <pre><code>#include "myclass.hpp" int main() { myclass m; m.barf(); return 0; } </code></pre> <p>And I use this implementation of myclass:</p> <p>myclassA.cpp:</p> <pre><code>#include &lt;iostream&gt; using namespace std; class myclass { // or include myclass.hpp, it both works fine public: myclass(); void barf(); }; myclass::myclass() { } //empty void myclass::barf() { cout &lt;&lt; "barfing\n"; } </code></pre> <p>then everything is OK. But if I use this implementation of myclass, which is exactly the same except the members are defined inside the class definition, I get a linking error:</p> <p>myclassB.cpp:</p> <pre><code>#include &lt;iostream&gt; using namespace std; class myclass { public: myclass() { } void barf() { cout &lt;&lt; "barfing\n"; } }; </code></pre> <p>The error I get:</p> <pre><code>$ g++ myclassB.cpp mymain.cpp /tmp/cc4DTnDl.o: In function `main': mymain.cpp:(.text+0xd): undefined reference to `myclass::myclass()' mymain.cpp:(.text+0x16): undefined reference to `myclass::barf()' collect2: ld returned 1 exit status </code></pre> <p>Apparently the object file built from myclassB.cpp doesn't export the member functions. Why aren't both of these implementations behaving te same? Is there some gotcha rule in C++ that says member definitions inside class definitions are not globally visible, but they are if they are defined outside of the class? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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