views:

280

answers:

2

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

+3  A: 

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:

public void exportRows(String^ text);

then you can define:

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

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.

e.James
OkI feel really dumb right now but thanks! =)
Eric
Well, don't feel dumb. We all had to ask such questions at some point in our careers!
e.James
A: 

In C++ you can only forward declare a class if you are not calling a method on a pointer or reference to that class. Any time you attempt to call a method on a class pointer or reference, you need to have the class definition available.

Deleting an incomplete type is legal, but very dangerous.

Please use a different tag than C++, as this is not C++.