Class in a class, default Constructor?
hi, i have the problem of having a class in a class, and when i declare the outer class, I dont know how to insert the constructors for the ones inside... example
class INNERCLASS
public:
{
int bob;
INNERCLASS(int initbob);
}
class OUTERCLASS
public:
{
int number;
INNERCLASS jim;
OUTERCLASS( int initnumber);
}
in code somewhere:
INNERCLASS::INNERCLASS(int initbob)
{
bob = initbob;
}
OUTERCLASS::OUTERCLASS( int initnumber)
//something goes here i think
{
number = initnumber;
}
in game code:
OUTERCLASS stuart(6);
this throws the error
error C2512: ''INNERCLASS'' : no appropriate default constructor available
please tell me how i can insert the declarations of the innerclases to the outer classes constructor, i think it goes where i marked "//something goes here i think"
Hope i made sense, i know its confusing, but i really cant use pointers to sort this out!
Yratelev
Managing Director -
DarkArrow Systems
"Better Quality Russian Technology"
Your problem isn''t really a "class in a class"; it''s simply the lack of a default constructor:
It''s a good idea to implement a default constructor so that you never have constructed but invalid objects in your programs. Lookup RAII.
class A{public: A(); // default constructor is a constructor called with no arguments private: // blah}; class B{public: B(int n = 0); // another way to specify a default constructor // is with default arguments private: A a;}; B::B(int n){ // whatever. A::A() called for a.}
It''s a good idea to implement a default constructor so that you never have constructed but invalid objects in your programs. Lookup RAII.
First use the source or code tags, find out about them in the Forum FAQ
Second change the class code to this
That should solve your problem
EDIT - Oluseyi's idea would work as well but this will allow you to keep the same constructor in INNERCLASS
[edited by - Grambo on September 1, 2002 5:50:38 PM]
Second change the class code to this
class INNERCLASSpublic:{int bob;INNERCLASS(int initbob);}class OUTERCLASSpublic:{int number;INNERCLASS jim;OUTERCLASS( int initnumber);}in code somewhere:INNERCLASS::INNERCLASS(int initbob){bob = initbob;}OUTERCLASS::OUTERCLASS( int initnumber):jim(somevariable)//some variable is whatever variable you want to pass to the INNERCLASS constructor{number = initnumber;}
That should solve your problem
EDIT - Oluseyi's idea would work as well but this will allow you to keep the same constructor in INNERCLASS
[edited by - Grambo on September 1, 2002 5:50:38 PM]
Try making your definition of the OUTERCLASS constructor look like this: OUTERCLASS::OUTERCLASS(@param) : jim(variable_you_want_to_use)
not sure if it''ll work tho''.
not sure if it''ll work tho''.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement