Reputation: 818
I'm doing a small program, just to play with classes. And I've made two classes, a and b.
I want to be able to access a in b and vice versa. This is what I got so far:
#ifndef A_HH_
#define A_HH_
#include <string>
class b;
class a
{
private:
string aString;
b* bClass;
public:
a(){aString = "A";}
string getString(){return aString;}
string getBString(){return bClass->bString;}
};
#endif /* A_HH_ */
and b:
#ifndef B_HH_
#define B_HH_
#include <string>
class a;
class b
{
private:
string bString;
a* aClass;
public:
b(){bString = "B";}
string getString(){return bString;}
};
#endif /* B_HH_ */
I want to be able to access the pointer not just store it. How can I do that?
Upvotes: 0
Views: 118
Reputation: 1387
You might use templating:
for a:
#ifndef A_HH_
#define A_HH_
#include <string>
#include "b.h"
class a
{
private:
string aString;
b* bClass;
public:
a()
{
aString = "A";
bClass = new b<a>;
}
string getString(){return aString;}
string getBString(){return bClass->getString();}
};
#endif /* A_HH_ */
and for b:
#ifndef B_HH_
#define B_HH_
#include <string>
template <typename T>
class b
{
private:
string bString;
T* aClass;
public:
b()
{
bString = "B";
aClass = new T;
}
string getString(){return bString;}
string getAString(){return aClass->getString();}
};
#endif /* B_HH_ */
This removes the circular dependency
Upvotes: 0
Reputation: 2539
In short, to access members of a struct or a class, you need to meet two conditions:
To overcome 1. you can either make the member public, or declare the accessing class or method as friend
, or better use a getter method.
To overcome 2., you need to include the header of the referenced class.
Upvotes: 0
Reputation: 409196
The problem is that you use the bClass
pointer in class a
, for that you need the definition of class b
. In this case this can be solved by simply including b.hh
in a.hh
. This simple solution will work as you're only declaring an a
pointer (but don't access it) in the class b
. A forward declaration is not enough, because it doesn't actually tells the compiler anything more than that the class b
exist.
Oh, and you need to change the bClass->bString
in a::getBString
to bClass->getString()
, as b::bString
is private. And of course create an actual instance of b
and assign it to bClass
.
Upvotes: 1