I have a problem with C++ project. I'm using resharper c++ for visual studio 2017 if thats relevant.
When I have 2 classes (A, B) and they include each other, sometimes resharper blacks out #include "A.h" in B as it would be unused, even if I have some use of A in class B, and I can't compile, because it doesn't know what "A" is.
Resharper even offers to add #include "A.h" for me, but if i click to accept it, it says:
cannot perform this action most likely because of errors in the source code
I can "fix" it by adding "class A;" just before declaring class B, but then it sees A as it would not have any methods or fields.
Here is minimal complete example of code that generates the error.
A.h file
#ifndef A_H
#define A_H
#include "B.h"
class A
{
public:
B** bs;
A() : bs(new B*[5])
{
for (int i = 0; i < 5; i++)
{
bs[i] = nullptr;
}
};
void do_something_in_A()
{
//something
}
};
#endif
B.h file
#ifndef B_H
#define B_H
#include "A.h"
class A; //if I don't add it I can't compile, if I add it I cannot access methods and fields in A as shown below
class B
{
public:
A* a;
B(A* a) : a(a) {};
void do_something_in_B()
{
//a->do_something_in_A(); doesn't work
}
};
#endif
main.cpp file
#pragma once
#include <iostream>
#include "A.h"
int main()
{
A a;
system("pause");
return 0;
}
I think that error could be created by circular dependency, but I couldn't find any working solution after searching for it quite long.
If possible, I would like to get not only the answer how to fix it, but some kind of explanation how it works and why is it wrong, so I can avoid similar errors in the future.
I hope I the error well enough. Thank you in advance for any answers.