From: Goran on
On Feb 15, 10:05 pm, Brad Gillespie <Brad
Gilles...(a)discussions.microsoft.com> wrote:
> Thus far, I have been creating classes that have objects in the header file.  
> E.g., I might create a dialog box class, and in the *.h file for the dialog
> box class, I have instantiated various objects, such as tab controls or list
> controls, etc.  So the dialog class “has-a” list control, for instance.
>
> However, I have run into a severe limitation.  I can’t use alternative
> constructors (Overloaded Constructors) when doing this, because I can’t
> include any pass parameters when instantiating an object in the *.h file of
> some other class.
>
> Let me clarify.  If I create a dialog class called DialogA, then in the *.h
> file for that class, I cannot instantiate a member object by passing
> variables to the constructor of that object’s class.  That is, in the
> DialogA.h file,
>
> CMyListCtrl  ListCtrlObj;                      // I can say this
>
> CMyListCtrl  ListCtrlObj(123,’M’);       // I can’t say this

It looks like you are looking for this:

header:
class CMyDialog : public CDialog
{
public:
CMyDialog(CWnd* pParent, int listParam1, char ListParam2);
}

implementation (or inline):
CMyDialog::CMyDialog(CWnd* pParent, int listParam1, char listParam2) :
CDialog(IDD, pParent), ListCtrlObj(listParam1, listParam2)
{}

Please don't take offense, but it also looks like you should not be
using MFC yet, you should instead learn more about the language
itself.

Goran.
From: David Wilkinson on
Brad Gillespie wrote:
> Thus far, I have been creating classes that have objects in the header file.
> E.g., I might create a dialog box class, and in the *.h file for the dialog
> box class, I have instantiated various objects, such as tab controls or list
> controls, etc. So the dialog class “has-a” list control, for instance.
>
> However, I have run into a severe limitation. I can't use alternative
> constructors (Overloaded Constructors) when doing this, because I can't
> include any pass parameters when instantiating an object in the *.h file of
> some other class.

Brad:

The concept others are telling you about is called the "initializer list".

You are probably familiar with providing parameters for the base class in the
initializer list, but what you are missing is that you can also provide
parameters for members. The different items (base and members) are separated by
commas.

There is also something wrong with your terminology:

First of all, when you say "in the .h file", you really mean "in the class
definition". Class definitions do not have to be in a .h file, though this is a
common way of organizing code.

Second, you do not "create" member objects in the class definition, you
"declare" them. They are not created until the object itself is created, and
that is why the constructor parameters are supplied in the initializer list, not
in the class definition.

--
David Wilkinson
Visual C++ MVP