I’m using C++ .NET 2.0
I have 2 forms
the first one is declared as follow
#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 one goes like this
#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 to the question! The line in SubForm causes the compiler to tell me ‘use of undefined type myNamespace::frmMain
I really have no clue about why the ‘ref class frmMain’ doesnt solve this problem
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 SubForm before frmMain has been defined, leading to the error.
The proper way to solve this problem is to keep all of the code for your classes in the appropriate source file, and not in the header. If your header file simply declares:
then you can define:
in SubForm.cpp, and everything should work out splendidly.
edit: Good Object-Oriented design involves separating interface from implementation, and the best way to to this in C++ is to keep interfaces in header files and implementation code in the corresponding source files.
The bottom line is that your header files should contain only declarations. Think of these as the interface to your classes. The header file shows only the function signatures that your class will implement. The source files, on the other hand, contain all of the definitions, which are the implementation of your classes.