Could someone explain why I receive a syntax error: Identifier 'Bar' during building without the inclusion of class Bar;
in the foo.hpp
header file?
I don't receive any errors in Visual Studio 2019 before building, and the build order appears to be bar
, then foo
, then main
, so following the #include
statements it would seem as though the bar
header file is first included inside the foo
header during the build.
I have included code below outlining the basic problem.
//Foo header file
#pragma once
#include "bar.hpp"
#include <iostream>
class Bar; //Commenting this line out results in no longer being able to build the project
class Foo {
public:
Foo();
void pickSomething(Bar& bar);
};
//Foo cpp file
#include "foo.hpp"
Foo::Foo() {
std::cout << "Made Foo" << std::endl;
}
void Foo::pickSomething(Bar& bar) {
bar.getSomething();
std::cout << "Picked something!" << std::endl;
}
//Bar header file
#pragma once
#include "foo.hpp"
#include <iostream>
class Foo;
class Bar {
public:
Bar(Foo& foo);
void getSomething();
};
//Bar cpp file
#include "bar.hpp"
Bar::Bar(Foo& foo) {
std::cout << "Made bar" << std::endl;
}
void Bar::getSomething() {
std::cout << "Gave something!" << std::endl;
}
//main file
#include "foo.hpp"
#include "bar.hpp"
int main() {
Foo foo;
Bar bar(foo);
foo.pickSomething(bar);
return 0;
}