Mr.Tu
Mr.Tu

Reputation: 2733

In C++, I want two classes to access each other

I have two classes, class A and class B.

A.h -> A.cpp
B.h -> B.cpp

And then, I set B as a member in class A. Then, class A can access class B by

#include <B.h>   

But, how can I get the pointer of class A in class B and access the public member of class A?

I found some information about on the internet: a Cross-class. They said you can make it by setting the class B as a nested class in class A.

Do you have any other advice?

sorry. myCode: as follow..

class A:

#ifndef A
#define A

#include "B.h"

class A
{
public:
    A() {
        b = new B(this);
    }

private:
    B* b;
};

#endif


#ifndef B
#define B

#include"A.h"

class B
{
public:
    B(A* parent = 0) {
        this->parent = parent;
    }

private:
    A* parent;
};

#endif

Upvotes: 0

Views: 2978

Answers (1)

vines
vines

Reputation: 5225

Just use forward declaration. Like:

A.h:

#ifndef A_h
#define A_h

class B; // B forward-declaration

class A // A definition
{
public:
    B * pb; // legal, we don't need B's definition to declare a pointer to B 
    B b;    // illegal! B is an incomplete type here
    void method();
};

#endif

B.h:

#ifndef B_h
#define B_h

#include "A.h" // including definition of A

class B // definition of B
{
public:
    A * pa; // legal, pointer is always a pointer
    A a;    // legal too, since we've included A's *definition* already
    void method();
};

#endif

A.cpp

#inlude "A.h"
#incude "B.h"

A::method()
{
    pb->method(); // we've included the definition of B already,
                  // and now we can access its members via the pointer.
}

B.cpp

#inlude "A.h"
#incude "B.h"

B::method()
{
    pa->method(); // we've included the definition of A already
    a.method();   // ...or like this, if we want B to own an instance of A,
                  // rather than just refer to it by a pointer.
}

Knowing that B is a class is enough for compiler to define pointer to B, whatever B is. Of course, both .cpp files should include A.h and B.h to be able to access class members.

Upvotes: 7

Related Questions