Jedi Schmedi
Jedi Schmedi

Reputation: 818

error: forward declaration, how to access pointer

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

Answers (3)

Ben J
Ben J

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

Marco Pantaleoni
Marco Pantaleoni

Reputation: 2539

In short, to access members of a struct or a class, you need to meet two conditions:

  1. the accessing element (class, method, ...) must have access "rights" to the referenced member
  2. the definition of the struct/class must be available.

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

Some programmer dude
Some programmer dude

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

Related Questions