title: Upcasting in C (learning class inheritance)
body: <p>Thanks for taking a look at my post, hopefully it will be relatively simple.</p>
  
  <p>I am attempting to learn more about QP/C or QP/nano, but as part of understanding how it works I need to learn about OOP concepts in C. Which is detailed in:</p>
  
  <p><a href="https://www.state-machine.com/doc/AN_OOP_in_C.pdf" rel="nofollow noreferrer">https://www.state-machine.com/doc/AN_OOP_in_C.pdf</a></p>
  
  <p>I have worked through the encapsualation portion of the OOP document and now am working to understand inheritance. In the document they show two ways of upcasting from the inherited class to a super class:</p>
  
  <pre><code>Shape_moveBy((Shape *)&amp;r1, -2, 3);
  </code></pre>
  
  <p>and then</p>
  
  <pre><code>Shape_moveBy(&amp;r2-&gt;super, 2, -1);
  </code></pre>
  
  <p>But I can't get this code to work?</p>
  
  <p>To understand this concept I tried to make some example code:</p>
  
  <pre><code>/****************** Inheritance Example ***********************/
  
  #include &lt;stdint.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  /* Shape Class */
  typedef struct
  {
      int16_t x; /* x-coordinate of shape's position */
      int16_t y; /* y-coordinate of shape's position */
  } Shape;
  
  void Shape_ctor(Shape * const me, int16_t x, int16_t y);
  void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy);
  
  void Shape_ctor(Shape * const me, int16_t, int16_t y)
  {
      me-&gt;x = x;
      me-&gt;y = y;
  }
  
  void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy)
  {
      me-&gt;x += dx;
      me-&gt;y += dy;
  }
  /* End Shape Class */
  
  /* Rectangle Class (Inherited Class below Shape) */
  typedef struct
  {
      Shape super; // inherits shape attributes
      uint16_t width;
      uint16_t height;
  } Rectangle;
  
  void Rectangle_ctor(Rectangle * const me, int16_t x, intt16_t y, 
                      uint16_t width, uint16_t height);
  
  Void Rectangle_ctor(Rectangle * const me, int16_t x, intt16_t y, 
                      uint16_t width, uint16_t height)
  {
      Shape_ctor(&amp;me-&gt;super, x, y);
      me-&gt;width = width;
      me-&gt;height = height;
  }
  /* End Rectangle Class */
  
  int main()
  {
  Rectangle r1, r2;
  
  // construct rectangles
  Rectangle_ctor(&amp;r1, 0, 2, 10, 15);
  Rectangle_ctor(&amp;r2, -1, 3, 5, 8);
  
  // operate on the shape
  Shape_moveBy((Shape *)&amp;r1, 2, 3);
  Shape_moveBy(&amp;r2-&gt;super, 2,-1); 
  
  return 0;
  }
  </code></pre>
  
  <p>when I compile I get the error</p>
  
  <pre><code>oop_inher.c In function 'main'
  oop_inher.c:77:17: error: invalid type argument '-&gt;' (have 'Rectangle {aska struct &lt;anonymous&gt;}')
   Shape_moveBy(&amp;r2-&gt;super, 2,-1);
  </code></pre>
  
  <p>I am guessing I am not using pointers correctly here, but since I am attempting upcasting I have a hard time following what I am doing wrong.</p>