1

header.h

class Foo{
public:
void fooFunction(std::map <std::string, Bar> &);
}

class Bar{
public:
void barFunction(std::map <std::string, Foo> &, Foo &);
}

When I try to compile this, I get an error saying Bar is not declared in the scope of fooFunction, and when I switch the order of the declarations, I get an error saying Foo is not in the scope of barFunction.

How can I make them be in the scope of each other? If I need multiple header files, how should I set that up in my makefile and #include s?

paddy
  • 60,864
  • 6
  • 61
  • 103
  • 1
    Possible duplicate of [Resolve build errors due to circular dependency amongst classes](https://stackoverflow.com/questions/625799/resolve-build-errors-due-to-circular-dependency-amongst-classes) –  Jul 25 '19 at 03:42

1 Answers1

2

You can simply forward-declare the other class in the header that requires it:

class Bar;

class Foo
{
public:
    void fooFunction(std::map <std::string, Bar>&);
};

class Bar
{
public:
    void barFunction(std::map<std::string, Foo>&, Foo &);
};

This works provided that Foo does not use Bar by value anywhere until after Bar has been defined. That means storing it as a member, passing as parameter, returning value of that type. In this case you're fine, since the Foo parameters are passed by reference.

Note that even though your std::map stores type Bar by value, this is still okay because it's a template and is not resolved until you use it, at which time Bar will be defined.

paddy
  • 60,864
  • 6
  • 61
  • 103
  • You could declare it right where it's used (`std::map&`) but it's probably clearer how you have it. – David G Jul 25 '19 at 02:31