title: Can instantiate a virtual object on the heap, but not on the stack?
body: <p>Let me preface this by saying I'm coming from a Java background, so please forgive me if I've made some stupid mistake here....</p>
  
  <p>I'm writing a C++ library that I would like to make compatible with both Arduino as well as the RaspberryPi. Most of the code is just clean, standard C++, but a few functions are hardware-specific (GPIO calls, for instance). Being from a Java background, I thought, I'll just create a HAL interface that defines those hardware-specific functions, and then I can create implementations of that interface for the RPi and Arduino, only to find out that interfaces are not a thing in C++ and you have to use virtual methods instead. <strong>Please see the bottom of my question for my source files.</strong></p>
  
  <p>However, when I went to actually use this, I discovered something quite strange: using the HAL on the heap compiles, but using it on the stack does not</p>
  
  <pre><code>//THIS DOES NOT COMPILE
  MyLibraryHAL hal = HAL_RaspberryPi();
  hal.someHwSpecificFunction(65);
  
  //BUT THIS DOES
  MyLibraryHAL* hal = new HAL_RaspberryPi();
  hal-&gt;someHwSpecificFunction(65);
  </code></pre>
  
  <p>The error is:<br>
  <code>src.ino:67: undefined reference to MyLibraryHAL::someHwSpecificFunction(unsigned char)</code>.</p>
  
  <p>Why is this? Is this just a feature of how virtual methods work? Or is there some concept I'm missing here?</p>
  
  <hr>
  
  <p><code>MyLibraryHAL.h</code></p>
  
  <pre><code>#include &lt;stdint.h&gt;
  
  #ifndef MyLibraryHAL_h
  #define MyLibraryHAL_h
  
  class MyLibraryHAL
  {
      public:
          virtual void someHwSpecificFunction(uint8_t param);
  };
  
  #endif
  </code></pre>
  
  <p><code>HAL_Arduino.h</code></p>
  
  <pre><code>#include &lt;stdint.h&gt;
  #include "MyLibraryHAL.h"
  
  #ifndef HAL_Arduino_h
  #define HAL_Arduino_h
  
  class HAL_Arduino : public MyLibraryHAL
  {
      public:
          void someHwSpecificFunction(uint8_t param);
  };
  
  #endif
  </code></pre>
  
  <p><code>HAL_Arduino.cpp</code></p>
  
  <pre><code>#include &lt;stdint.h&gt;
  #include "HAL_Arduino.h"
  
  void HAL_Arduino::someHwSpecificFunction(uint8_t param)
  {
      //do things
  }
  </code></pre>
  
  <p><code>HAL_RaspberryPi.h</code></p>
  
  <pre><code>#include &lt;stdint.h&gt;
  #include "MyLibraryHAL.h"
  
  #ifndef HAL_RaspberryPi_h
  #define HAL_RapsberryPi_h
  
  class HAL_RaspberryPi : public MyLibraryHAL
  {
      public:
          void someHwSpecificFunction(uint8_t param);
  };
  
  #endif
  </code></pre>
  
  <p><code>HAL_RaspberryPi.cpp</code></p>
  
  <pre><code>#include &lt;stdint.h&gt;
  #include "HAL_RaspberryPi.h"
  
  void HAL_RaspberryPi::someHwSpecificFunction(uint8_t param)
  {
      //do things
  }
  </code></pre>