Search code examples
c++classoopforward-declarationincomplete-type

How do you create a class which can hold itself as a variable in c++?


I'm fairly new to c++ with most of my writing having been in Python.

In Python, if I wanted to create a class to hold information about a Human, I could write a class which could hold its 'parent' as one of its variables. In Python, I'd do it roughly like this:

class Human:

    def __init__(self, name):
        self.name = name


first = Human("first")
second = Human("second")

second.parent = first

where second.parent = first is saying that the parent of the Human second is the Human first.

In c++ I tried to implement something similar:

class Human {

    public:
        Human parent;

};

int main() {
    Human first = Human();
    Human second = Human();

    second.parent = first;
}

This example comes with an error that field has incomplete type: Human. I get this, because it's saying that I can't have a Human in my Human object because there isn't yet a full definition of what a Human is. When I search for related posts, I keep coming up against solutions using forward declaration and pointers but I haven't been able to make it work properly.

I'd really appreciate any help in making the c++ example behave how I want it to.

Thanks.


Solution

  • For example by using pointers:

    struct Human
    {
        Human* parent;  // The symbol Human is declared, it's okay to use pointers to incomplete structures
    };
    
    int main()
    {
        Human first = Human();
        Human second = Human();
    
        second.parent = &first;  // The & operator is the address-of operator, &first returns a pointer to first
    }
    

    You can use references as well but those could be a little harder to work with and initialize.