Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do you declare a class variable without initiallising it? 1

Status
Not open for further replies.

besmith

Programmer
Apr 29, 2003
1
AU
How do you declare a class variable without initiallising it?

I would like to be able to declare a variable of type AClass outside of any methods within my class, without initiallising the variable until the constructor is called (i.e. initiallise the variable within the constructor). This way, the variable would be accessible throughout the class.

For example, what I would like:

/***START CODE***/

class MyClass{

private:
//Like in Java- just declare, don't initiallise.
ANamespace::AClass AClassInstance;

public:
MyClass(){
// Initiallise here.
AClassInstance(new ClassBody());
}
}

/***END CODE***/

The above does not work, because it seems that you can't just declare an class variable in C++ without initiallising it. Or can you??

Is there a way to declare a class variable without instantiating it?

Any help would be greatly appreciated.

Thanks,
Brad.
 
Have you tried making the class member a pointer to the variable, Then in the constructor, just Get a new instance.
 
Brad,

To initialize a class using one of it's constructors you must use the C++ initialization list. If you have any books that discuss the fundamentals of the C++ language it should have a section on the initialization list syntax. For your classes constructor you would change it to this:
[/code]
MyClass(): AClassInstance(new ClassBody()){}
[/code]
-pete

 
Thanks Kalisto, Palbano you have been very helpfull. I used the pointer idea as follows, and it worked a treat:

/***START CODE***/

class MyClass{

private:
//Like in Java- just declare, don't initiallise.
ANamespace::AClass* AClassInstance;

public:
MyClass(){
// Initiallise here.
// This adds AClassInstance to the heap.
AClassInstance = new ANamespace::AClass();
}
}

/***END CODE***/

Bradius
C++/Java programmer
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top