Reputation: 519
I have two classes A and B defined in A.h, A.cpp and B.h, B.cpp respectively. Class A has a structure that I want to use in a function of Class B. Because Class B is included in Class A, I can't include class A in Class B as it will lead to circular dependency. Code for all the files are given below: A.h
#ifndef _A_H
#define _A_H
#include B.h
namespace common {
class A {
public:
static struct strctOfA {
float p1 = 2;
} structA;
void functionOfA();
};
}
#endif // !_A_H
A.cpp
#include A.h
using namespace common;
A::functionOfA() {
B b;
b.functionOfB(structA);
}
B.h
#ifndef _B_H
#define _B_H
namespace common {
class B {
public:
functionOfB(??);
};
}
#endif // !_B_H
B.cpp
#include B.h
using namespace common;
B::functionOfB(??) {
// Want to use structA here;
}
I looked into StackOverflow and found a thread quite close to my problem, however, they it either doesn't explains the answer or I am not able to understand their solution. Please help me with this.
Thanks
Update Thanks I-V for pointing out the mistake and providing me the explanation. Updating the code worked for me. Thanks everyone for providing additional knowledge to my C/C++ coding skills. :)
Upvotes: 2
Views: 4942
Reputation: 743
The solution is simple, what you wrote is a bad habit.
There is no reason to include B.h in A.h because you don't use any part of B.h in the A.h file. A better way to implement it is to include B.h in A.cpp and not in the header file.
It will also solve the cycle of includes you have..
In general, it is recommended to include files in .cpp file and NOT in header files when you don't use functions/objects of the included file in the header file :)
In addition, you should use #pragma once for Windows or ifndef for anything else in order to be safe of conflicts
A.h
#ifndef _A_H
#define _A_H
namespace common {
class A {
public:
static struct strctOfA {
float p1 = 2;
} structA;
}
}
#endif
A.cpp
#include A.h
#include B.h
using namespace common;
class A {
B b;
b.functionOfB(structA);
}
NOTE: from B.cpp include A.h
Upvotes: 3
Reputation: 832
That can be done with forward-declarations, unless you abolutely must pass it by value. But I can't think of a scenario where this wouldn't work with references.
A.h
#ifndef A_H_
#define A_H_
struct B;
struct A {void f(B&);};
#endif
A.cpp
#include "B.h"
void A::f(B & value) {/* do something */ };
B.h
#ifndef B_H_
#define B_H_
struct A;
struct B {void f(B&);};
#endif
B.cpp
#include "A.h"
void B::f(A & value) {/* do something */ };
If you need to have a value of B in A with only a forward-declaration you can put it in a pointer, i.e. use a std::unique_ptr.
Upvotes: 0