0

I have the following program in which I have 2 classes, namely Class A and Class B in which each class has instance of another class declared as a private member.

FYI, for one class I'm using dynamic allocation (pointer instance) and in the other class I'm using automatic allocation (normal instance).

(Program.h)

class A;
class B;

class A
{
    A();
    ~A();
    public:
    void InitA();
    void funcA;
    private:
    B b; // ERROR! on code compilation: "A::b uses undefined class B"
}

class B
{
    B();
    ~B();
    public:
    void InitB();
    void funcB;
    private:
    A *a;
}
</code>

(Program.cpp)

 B::B() : a(new A())
    {
    }
    B::~B() 
    { 
        SAFE_DELETE (a); 
    }
    B::InitB()
    {
        a->funcA(); // works beautifully!
    }


    A::A() 
    {
    }
    A::~A() 
    { 

    }
    A::InitA()
    {
        b.funcB(); // DUE TO ERROR, code never compiles so I don't see this.
    }

ERROR: "A::b uses undefined class B"

Now, I've deliberately not declared a pointer instance of class B in class A, which I believe should not be the reason for this error. This error is probably because I'm not doing forward declaration properly.

cryengineplus
  • 61
  • 1
  • 3
  • I believe in header file, mere re positioning the classes should do the job for you. Means declare class B before you declare class A. Class A looks for an instance of class B whose declaration is not visible at that point of time. BUT Class B will just require the pointer to class A which can be achieved by forward declaring class A. – PRIME Dec 12 '15 at 05:54
  • The referenced duplicate question explains why forward declaration doesn't help in your case. It deserves reading, but shortly: forward declaration isn't enough for member object, though it's fine for pointers. – tonytony Dec 12 '15 at 06:19

0 Answers0