forward declaration problems

Hi there,

I'm wondering how to get this working:
-I have a class "B" that has a variable of class "A".
-Objects of Class "A" have a pointer to the original "creator object" of class "B" so they can access the original instance.

The file looks a bit like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class B;
class A
{
public:
    A() : _p(NULL) {}
    A(B* p) : _p(p) {}
    void TestFunc(int val) {
        _p->SetVal(val);
    }
private:
    B* _p;
};

class B {
public:
    B(int v) : val(v) {
        s =A(this);
    }
    void SetVal(int v) {
        val = v;
    }
    void TestFunc(int val) {
        s.TestFunc(val);
    }
private:
    A s;
    int val;
};


However this gives me a compile error:
1>X\main.cpp(9) : error C2027: use of undefined type 'B'
1> X\main.cpp(2) : see declaration of 'B'


Causes/how to create this?


_p->SetVal(val);

You can't inline this just with a forward declaration. Remember, a forward declaration knows nothing about the class, it only allows you to use pointers or references, not methods.

EDIT:
-Objects of Class "A" have a pointer to the original "creator object" of class "B" so they can access the original instance.

Also notice this shouldn't be necessary at all. If A has a pointer to an object of type B, A should know how to manipulate B, but B shouldn't know anything about A.
Last edited on
@filipe: I'm afraid I don't fully understand what you are saying there (in the edit).
As you can see in the "example": "A" can manipulate "B", however "A" ought to be accessed only from "B"..

Let's put it more into english words:
Suppose I have a "Car" (object "B").. That care has a certain "state" (object A) which defines what it is doing (parking, driving, etc)..

Then what I would like to do is: let "Car" call: "State.doit()".. State.doit should then access the car object who called the function & update the car object (position, speed etc).
Such simple states could be held in an enumeration:

1
2
3
4
5
6
7
8
9
class Car {
public:
    // ...
    enum State { parked, parking, driving };

private:
    // ...
    State state;
};

Car's methods would ensure the state variable gets set to a proper value when needed. They could also check the state to verify which behavior they're looking for. If states get too complicated, they could be a local class, since they only make sense inside the class.
Last edited on
Problem with enumerates is that I have to "link" it to the function I would use when calling "doit" (in the class one of the members should simply be a functor)..

I'd like to make system where extending (thus adding an extra state & all code that belongs to this state) is very easily possible.
Topic archived. No new replies allowed.