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

后端 未结 4 1009
我寻月下人不归
我寻月下人不归 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:25

    I suppose one way is to make abstract interface classes with no members. Then subclass foo and bar from those interface classes.

    e.g.:

    class FooInterface
    {
       // methods here
    }
    
    class BarInterface
    {
       // methods here
    }
    
    class Foo : public FooInterface
    {
       BarInterface *pBar;
    }
    
    class Bar : public BarInterface
    {
       FooInterface *pFoo;
    }
    

    This breaks the cycle of dependencies (unless the interfaces themselves depend on each other, and if that's the case then they should probably be declared in the same file)

提交回复
热议问题