title: Mixing C-Style Structures with C++
body: <p>I'm no C++ expect, as you will undoubtedly notice. But I'm trying to "upgrade" some old C code to C++.  In the process, I'm trying to promote old structures to classes.  I found this Oracle article about some of the things I'm trying to do. </p>
  
  <p><a href="http://www.oracle.com/technetwork/articles/servers-storage-dev/mixingcandcpluspluscode-305840.html" rel="nofollow">http://www.oracle.com/technetwork/articles/servers-storage-dev/mixingcandcpluspluscode-305840.html</a></p>
  
  <p>But 2 things. The article doesn't address a more complicated case I have. And my "workaround" doesn't seem to lead consistent results. So here I go with some details.</p>
  
  <p>Old C-Style structure:</p>
  
  <pre><code>typedef struct
  {
      int ia;
      float fa;
      ...
  } Struct_A;
  
  typedef struct
  {
      Struct_A sA;
      int ib;
      float fb;
      ...
  } Struct_B;
  </code></pre>
  
  <p>C++<br>
  According to the Oracle article, I should be able to promote Struct_A to a class and still be able to use the class version with old C functions. Here's apparently how:  </p>
  
  <pre><code>class CStruct_A : public Struct_A  // Inherits from C- Struct_A
  {
  public:
      CStruct_A() : ia(0), fa(0.0f) {}
  }
  </code></pre>
  
  <p>Pause. Right here, I already have an issue. I can't seem to initialize the C-Structure elements as indicated in the article and as shown above. The compiler doesn't accept it.  I have to re-write the class as:  </p>
  
  <pre><code>class CStruct_A : public Struct_A
  {
  public:
      CStruct_A()
      {
          ia = 0;
          fa = 0.0f;
      }
  }
  </code></pre>
  
  <p>So that's the first question mark. Not a huge deal but the article claims it can be done.  </p>
  
  <p>Next, the tougher issue.  Promoting the Struct_B, which contains a Struct_A member.  I want to make sure Class A's constructor is used to initialize the variables.  But I'm not sure how to force it.  In my c++ code, if I have something like:  </p>
  
  <pre><code>{
      CStruct_B *pCStrb = new CStruct_B();
      ...
  }
  </code></pre>
  
  <p>Class B's constructor gets invoked but not class A's.  The workaround I have is lame... But that's the only thing I can figure out for now. I declare an internal private function ini() in class A, make class B a friend and call init() from class B's constructor.  </p>
  
  <pre><code>class CStruct_A : public Struct_A
  {
      friend class CStruct_B;
  
  public:
      CStruct_A() { init(); }
  
  private:
      void init()
      {
          ia = 0;
          fa = 0.0f;
      }
  }
  
  class CStruct_B : public Struct_B
  {
  
  public:
      CStruct_B()
      {
          ib = 0;
          fb = 0.0f;
          static_cast&lt;CStruct_A *&gt;(&amp;sA)-&gt;init();
      }
  }
  </code></pre>
  
  <p>I have more questions but this is probably already too long.</p>
  
  <p>Any help will be greatly appreciated. </p>