Note that there are some explanatory texts on larger screens.

plurals
  1. POConstructor in class with inheritance
    text
    copied!<p>I'm having some problems with inheritance and constructors in C++. What I've got is a class <code>VirtualMotor</code> which inherits <code>Motor</code> (is that the correct way to say it?). The class VirtualMotor should have it's own constructor, but I'm doing something wrong when I create it and the compiler gives me an error (se below). My source code is like this:</p> <h3>Motor.h</h3> <pre><code>class Motor { protected: float speed; float angle; public: Motor(); float getSpeed(); float getAngle(); virtual void setSpeed( float speed ); virtual void setAngle( float angle ); </code></pre> <h3>Motor.cpp</h3> <pre><code>#include "Motor.h" float Motor::getSpeed() { return speed; } float Motor::getAngle() { return angle; } </code></pre> <h3>VirtualMotor.h</h3> <pre><code>#include "Motor.h" class VirtualMotor: public Motor { private: float lastSpeed; public: VirtualMotor(); void setSpeed(float speed); void setAngle(float angle); }; </code></pre> <h3>VirtualMotor.cpp</h3> <pre><code>#include "VirtualMotor.h" VirtualMotor::VirtualMotor() { speed = 2; angle = 5; } void VirtualMotor::setSpeed(float speed) { this-&gt;speed = speed; } void VirtualMotor::setAngle(float angle) { this-&gt;angle = angle; } </code></pre> <h3>Main.cpp</h3> <pre><code>#include &lt;iostream&gt; #include "VirtualMotor.h" using namespace std; int main (int argc, char **argv) { VirtualMotor m; cout &lt;&lt; m.getSpeed() &lt;&lt; endl; m.setSpeed(9); cout &lt;&lt; m.getSpeed() &lt;&lt; endl; return 0; } </code></pre> <p>To compile I use the command <code>g++ Main.cpp Motor.cpp VirtualMotor.cpp -o main</code> and I get the following error:</p> <pre><code>/tmp/ccIdYJaR.o: In function `VirtualMotor::VirtualMotor()': VirtualMotor.cpp:(.text+0x29): undefined reference to `Motor::Motor()' /tmp/ccIdYJaR.o: In function `VirtualMotor::VirtualMotor()': VirtualMotor.cpp:(.text+0x5d): undefined reference to `Motor::Motor()' /tmp/ccIdYJaR.o:(.rodata._ZTI12VirtualMotor[typeinfo for VirtualMotor]+0x8): undefined reference to `typeinfo for Motor' collect2: ld returned 1 exit status </code></pre> <p>I feel there's a really simple solution to this, but I just can't see it. I've tried to use <code>VirtualMotor::VirtualMotor() : Motor::Motor()</code> and other variations without any luck.</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