O'Reilly logo

Mastering C++ Programming by Jeganathan Swaminathan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Circular dependency

Circular dependency is an issue that occurs if object A depends on B, and object B depends on A. Now let's see how this issue could be fixed with a combination of shared_ptr and weak_ptr, eventually breaking the circular dependency, as follows:

#include <iostream>#include <string>#include <memory>#include <sstream>using namespace std;class C;class A {      private:           weak_ptr<C> ptr;      public:           A() {                  cout << "\nA constructor" << endl;           }           ~A() {                  cout << "\nA destructor" << endl;           }           void setObject ( weak_ptr<C> ptr ) {                  this->ptr = ptr;           }};class B {      private:           weak_ptr<C> ptr;      public:           B() {               cout << "\nB constructor" << endl;           }                      ~B() {               cout << "\nB destructor" << endl;           }           void setObject ( weak_ptr<C> ptr ) {                this->ptr = ptr;           }};class C { ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required