What is the best way to deal with co-dependent classes in C++?

后端 未结 4 1015
我寻月下人不归
我寻月下人不归 2020-12-16 01:57

Say I have a class foo with an object of class bar as a member

class foo
{
    bar m_bar;
};

Now suppose bar needs to keep track of the foo

4条回答
  •  清酒与你
    2020-12-16 02:38

    In your example, foo depends on bar (because it contains an actual bar object), but bar does not depend on foo (since it only contains a foo *). Now bar does depend on on foo being a type name, so bar.h needs a forward declaration of the name: class foo;. foo depends on bar, so foo.h should contain #include "bar.h"

    You can't have classes that directly depend on each other in C++; it simply doesn't work. You need to decouple the classes such that one only depends on the other existing, like in your example. The only things that create a direct dependence are using a class as a base class or as a field; any other use just creates an indirect dependence, which is generally not a problem.

提交回复
热议问题