Object initialization

B

Bob Altman

This question deals with unmanaged C++ (Visual Studio 2005).

Suppose I have a class named MyClass with a constructor that takes an
argument. How do I create an instance of type MyClass as a member variable
(see below)?

Class Test
{
public:
Test(void); // Constructor
~Test(void); // Destructor

private:
MyClass m_myClass("My argument"); // error C2059; syntax error :
'constant'
};

TIA - Bob
 
D

David Lowndes

Suppose I have a class named MyClass with a constructor that takes an
argument. How do I create an instance of type MyClass as a member variable
(see below)?

Class Test
{
public:
Test(void); // Constructor
~Test(void); // Destructor

private:
MyClass m_myClass("My argument"); // error C2059; syntax error :
'constant'
};

Bob,

I think you'd do it like this:


Test() : m_myClass( "Hello" )
{
}

private:
MyClass m_myClass;

Dave
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top