Forward declaration problem

I am using C ++. NET 2.0

I have 2 forms

the first is declared like this

#include "stdafx.h"
    namespace myNamespace{

      public ref class frmMain : public System::Windows::Forms::Form {
      /*... snip ...*/
      public void addNewRow(String^ text){ /*... snip... */  }
      public void launchSubForm() { SubForm^ sf = gcnew SubForm(this); sf->Show(); }

      };
    }

      

the second goes as follows

#include stdafx.h
    namespace myNamespace{
      ref class frmMain;
      public ref class SubForm : public System::Windows::Forms::Form {
      frmMain^ myMain;
      SubForm ( frmMain^ pMain){
        myMain = pMain;
      }
      /*... snip ...*/
      public void exportRows(String^ text){ /*... snip... */  }
        myMain->addNewRow("myNewText");   <--- This line causes compile error
      };
    }

      

in stdafx.h i have

/*... snip... */
#include "SubForm.h"
#include "frmMain.h"

      

Now the question! The line in SubForm makes the compiler tell me "using undefined like myNamespace :: frmMain

I really don't understand why "ref class frmMain" doesn't solve this problem.

+1


source to share


2 answers


This is because both of these header files include "stdafx.h" and stdafx.h includes "SubForm.h" before "frmMain.h".

So in "SubForm.h" the compiler wants to define the SubForm before frmMain is defined, which will result in an error.

The correct way to solve this problem is to keep all the code for your classes in the appropriate source file and not in the header. If your header file just declares:

public void exportRows(String^ text);
      

then you can define:



public void SubForm::exportRows(String^ text)
{
    /*... snip ...*/
    myMain->addNewRow("myNewText");
}
      

in SubForm.cpp and you should be fine.


edit: Good OO design involves decoupling interface from implementation, and the best way to do this in C ++ is to maintain interfaces in header files and implementation code in their respective source files. p>

The bottom line is that your header files should only contain declarations . Think of it as an interface to your classes. The header file only displays the signatures of the functions that will be implemented by your class. On the other hand, source files contain all the definitions that are the implementation of your classes.

+3


source


In C ++, you can only redirect a class declaration, unless you call a pointer or reference method to that class. Every time you try to call a pointer or class reference method, you need to have a class definition.

Removing an incomplete type is legal, but very dangerous.



Use a tag other than C ++ as this is not C ++.

0


source







All Articles