small_potato
small_potato

Reputation: 3207

circular class member pointer?

I am not sure if I can describe the problem, but I will try my best. Here is the situation:

If I can want a class1 has a pointer as a member variable pointing to another class, class2. Meanwhile, I want class2 also has a pointer as a member variable pointing to class1. Is that possible?

class Class1
{
private:
    Class2* classptr;
        ... ...
public:
        ... ...
};

class Class2
{
private:
    Class1* classptr;
        ... ...
public:
        ... ...
};

It appears to me that none of Class1 and Class2 has been recognized as an identifier. I guess none of Class1 and Class2 is created. Correct me if I am wrong.

Upvotes: 1

Views: 261

Answers (1)

anon
anon

Reputation:

You need a forward declaration. Either:

class Class1
{
private:
    class Class2* classptr;
        ... ...
public:
        ... ...
};

or:

class Class2;

class Class1
{
private:
    Class2* classptr;
        ... ...
public:
        ... ...
};

Upvotes: 7

Related Questions