Re: Using derived classes as member variables works...sometimes
On Sun, 3 Sep 2006 13:03:01 -0700, Mkennedy1102
<Mkennedy1102@discussions.microsoft.com> wrote:
suppose i derive CMyDlg from CDialog, then I want to use a CMyDlg object as a
member variable of my main window (dialog based app). I add a member
variable of the type CMyDlg with the name myDlg, then later I use the
variable myDlg to call methods, retrieve data, etc....so why is it that when
I compile the code, I get errors that indicate that my compiler has no idea
what a CMyDlg is?
IE: "error C2146: syntax error : missing ';' before identifier 'myDlg'";
and "error C2501: 'CMyDlg' : missing storage-class or type specifiers"
I at times done this with no trouble at all, but sometimes I have to spend a
bunch of time adding/removing #include "MyDlg.h" to a varying array of my
other .h's and .cpp's
There never seems to be a logical pattern to what works and doesn't work, I
would assume, (and correct me please!) that I need to include the header only
in the classes that need to use the derived class (like my main window class)
but I have wound up with include statements riddled throughout my code in a
willy-nilly fashion just trying to get the compiler to recognize that my
derived class is actually there. So, what is it that I'm doing wrong?
It doesn't sound like you're doing anything wrong. You must #include a
header file to use the things it declares.
A little more background....
Just adding the myDlg member variable as a CMyDlg worked ok at
first......then I tried to add a CMainDlg pointer to CMyDlg as a member
variable and everything went screwy, is there a problem in trying to do that?
Even given that issue, once i removed that variable, my compiler seemed to
forget that just minutes ago, it knew what a CMyDlg was....
I'm so lost and frustrated, please help!
You could get into a circular dependency such that MyDlg.h needs to
#include MainDlg.h but MainDlg.h needs to #include MyDlg.h, which cannot
work. You can solve this by forward-declaring one of the types, e.g. in
MyDlg.h, write:
class CMainDlg;
Then you can declare pointers of this type in the header file:
CMainDlg* m_pMainDlg;
However, as the definition of CMainDlg isn't in scope, you can't use
m_pMainDlg in ways that require the definition, e.g. you can't call member
functions. But that's just in the header. In MyDlg.cpp, you would write:
#include "MainDlg.h"
Now code which follows in MyDlg.cpp, namely the implementation of CMyDlg,
can fully use m_pMainDlg.
--
Doug Harrison
Visual C++ MVP