Reputation: 2946
class A
{
class B;
B::data myData; //Error: incomplete type not allowed.
class B
{
public:
struct data
{
int number;
};
};
};
In the code above, how could I declare a member variable of type data in class A?
Upvotes: 2
Views: 1057
Reputation: 39354
Use scope specifiers and make sure you don't use the type until after its defined in the file:
class A
{
class B
{
public:
struct data
{
int number;
};
};
B::data myData;
};
Also, note that forward-declaration doesn't work unless you're just using a pointer to the class. When you create an instance of the class like you have, it needs the definition to that class available to it immediately.
Upvotes: 0
Reputation: 355367
B
must be defined before you use it in the declaration of A::myData
:
class A
{
class B
{
public:
struct data
{
int number;
};
};
B::data myData;
};
Upvotes: 3
Reputation: 17732
I think all you need to do is put the class definition in front of the declaration of the variable. The compiler has no idea what is inside class B
, only that it exists, until it encounters the actual definition of the class
Upvotes: 3