user2368055
user2368055

Reputation: 420

C++ class and interlinked objects forming a cycle

How could i achieve interlocked object structure that makes a cycle in C++

class Foo
{
    Bar bar;
};

class Bar
{
    Foo foo;
};

Upvotes: 3

Views: 984

Answers (2)

James Adkison
James Adkison

Reputation: 9602

Foo.h

#include <memory>

class Bar; // Forward declare Bar class

class Foo
{
public:
    Foo();

private:
    std::unique_ptr<Bar> bar; // Use pointer so that header include is not necessary
};

Foo.cpp

#include "Foo.h"
#include "Bar.h" // Now include bar (in the cpp file to avoid circular includes)

Foo::Foo() :
    bar(new Bar())
{
    // Do nothing
}

Use the same setup with Bar.h and Bar.cpp.

Edit 1

Note: The above code assumes a compiler supporting C++11 is used. However, if this is not the case then a raw pointer (e.g., Bar* bar) should be used and the destructor must be implented to call delete bar. This is necessary to avoid leaking the resource; of course the above assumes Foo and Bar owning their member pointer is the correct behavior for these classes but it can easily be changed this is not the correct assumption.

Upvotes: 6

mjs
mjs

Reputation: 3005

The usual means is by using forward declarations. To do this you should split these into seperate header files, eg

//foo.h
class Bar;

class Foo
{
     Bar* myBar; //Note this must be a pointer
     int someVal;
     int someFunc();

}


//bar.h
class Foo;
class Bar
{
     Foo* myFoo; //Again, must be a pointer
}

The header files should not include each other. There are some restrictions, in that you can only use pointer-to-foo and pointer-to-bar until the compiler has encountered the actual declaration. This is because the compiler knows how much memory to allocate for a pointer, however would not know how big the required object would be.

See also this answer which achieves the same thing, using smart pointers. My solution is a simpler, pure C++ version, however James Adikin's is probably preferable where supported.

Upvotes: 0

Related Questions