Leonardo Raele
Leonardo Raele

Reputation: 2824

Is there some way to create a class that have an object of a class that have an object of this class in C++?

In C++, is there some way to create a class that have, as attribute, an object of a class that have, as attribute, an object of the first class?

e.g.:

class A {
    B attribute;
public:
    A(){}
};

class B {
    A attribute;
public:
    B(){}
};

The code above does not compile. Is there some way to do something alike?

Thanks!

Upvotes: 1

Views: 104

Answers (3)

Ayjay
Ayjay

Reputation: 3433

You need to rethink your structure. You're trying to define a structure that contains another structure, which contains the first structure which contains the second structure, etc...

Upvotes: 0

omt66
omt66

Reputation: 5019

First, you need to forward declare your class B. If not, the compiler wouldn't know what the B is. Also, change the attributes to be pointers, or else you will still have a compiler error, even though you forward declared B, it still doesn't know the implementation yet!

The following code may help, good luck...

class B;

class A {
    B *attribute;
public:
    A(){}
};

class B {
    A *attribute;
public:
    B(){}
};

Upvotes: 6

Jollymorphic
Jollymorphic

Reputation: 3530

These definitions, even if you could use forward declaration to make them work (which you can't), are inherently recursive. An A contains a B, which contains an A, which contains a B, and on and on. It is nonsensical.

Upvotes: 2

Related Questions