Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing a method of a member object in C++
    text
    copied!<p>I am trying to access a method of an object (<code>myEOS.calc(...)</code>) from a method of an object (<code>myPlanet</code>) of another class containing an instance of the first class (<code>static EOS myEOS</code>):</p> <pre><code>// class in class class EOS { public: static float Y; float calc(float); }; float EOS::calc(float x){ return x; // some complicated calculation } class Planet { public: static EOS myEOS; // want only one instance; cf. below static void setX(float* X); // must be static; cf. below }; void Planet::setX(float* X) { *X = myEOS.calc(*X); // will give an error } int main(){ Planet myPlanet; } </code></pre> <p>This returns the linking-time error</p> <pre><code>In function `Planet::setX(float*)': test.cpp:(.text+0x1a): undefined reference to `Planet::myEOS' collect2: ld returned 1 exit status </code></pre> <p>Compiling separately, with <code>-c</code>, the classes and the main program (with an <code>#include</code> in the main file) gives no error; this looks like the key to the solution but I do not see the lock!</p> <p>Does someone know what the problem is? I hope my intent is clear from what I have, even if there is some fundamental misconception. I thought I somewhat understood classes and reread tutorials but saw no discussion of classes within classes (not nested classes). I was not able to find a similar question on this site (from which I can usually get all the answers I need!) either.</p> <p>By the way, following <a href="https://stackoverflow.com/questions/5058014/construction-of-object-with-non-default-constructor-inside-c-class">somebody else's question</a>, adding explicit constructors (and correctly initialising the EOS in Planet's initialiser list) did not remove the compiler complaint about "undefined reference to <code>Planet::myEOS'" (this done without the</code>static` keyword).</p> <p>Finally, note that <code>Planet::setX</code> needs to be static because a pointer to this method must have a "class-less" signature as it is passed to a function that cannot handle methods/classes:</p> <pre><code> void (*fun_ptr)(float*) = &amp; (Planet::setX); </code></pre> <p>This also forces the object <code>myEOS</code> to be static (needs to be accessed from a static function), and anyway the initialisation of <code>EOS</code> objects is expensive.</p> <p>Thanks a lot for anybody's help!</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