Home > Software engineering >  Recursive Type Dependencies in C
Recursive Type Dependencies in C

Time:07-10

#include <iostream>
#include <cstdlib>

class Egg;
class Chicken;

class Egg
{
public:
    Chicken *creator;
    Chicken getCreator()
    {
        if (!creator)
            return Chicken{};
        return *creator;
    }
};

class Chicken
{
public:
    Egg creator;
    Egg getCreator()
    {
        if (&creator == 0)
            return Egg{};
        return creator;
    }
};

void chicken_and_egg()
{

    Chicken chicken;
    Egg egg;
    chicken.creator = egg;
    egg.creator = &chicken;
    Egg e = chicken.getCreator();
    Chicken c = egg.getCreator();
    if (&(chicken.creator) == &(c.creator) && &(egg.creator) == &(e.creator))
    {
        using namespace std;
        cout << "the `Chicken and Egg' dilemma is solved!" << endl;
    }
}

int main()
{

    chicken_and_egg();

    return 0;
}

Does anybody know how to resolve the circular type dependencies in these two classes?

The creator in Egg class is reported to have incomplete type Chicken. I have tried to mess around with pointers but so far have found no clue.

CodePudding user response:

You need to define the member functions after the full definitions of the necessary classes have been seen. Example:

class Egg;
class Chicken;

class Egg {
public:
    Chicken* creator;
    Chicken getCreator(); // declaration only
};

class Chicken {
public:
    Egg creator;
    Egg getCreator(); // declaration only
};

// definitions:
Chicken Egg::getCreator() {
    if (!creator) return Chicken{};
    return *creator;
}

Egg Chicken::getCreator() {
    // strange comparison removed
    return creator;
}
  • Related