oldSkool
oldSkool

Reputation: 1232

friend classes with pointers to each other

How can I create two classes that have member pointers to each other's class type, with full access to each other's data? In other words, I need two classes like this:

class A
{
protected:
   B *p;
};

class B
{
protected:
   A *p;
};

I'm having trouble with it because I'm not up to par with C++ conventions, and obviously, class A can't declare a class B because B is declared later in the code.

Thanks for the help

Upvotes: 2

Views: 2991

Answers (7)

Steve Jessop
Steve Jessop

Reputation: 279285

class B;
class A {
    friend class B;
  protected:
    B *p;
};

class B {
    friend class A;
  protected:
    A *p;
};

Note that any member functions of A which actually use the members of B will have to be defined after the definition of B, for example:

class B;
class A {
    friend class B;
  protected:
    B *p;
    A *getBA();
};

class B {
    friend class A;
  protected:
    A *p;
};

A *A::getBA() { return p->p; }

Upvotes: 2

bcsanches
bcsanches

Reputation: 2372

simple use: class B;

class A
{
    protected:
       B *p;
       friend class B;
};

class B
{
    protected:
       A *p;
       friend class A;
};

Using class B; means a forward declaration and this basically tells the compiler: "class B exists somewhere".

Upvotes: 1

Stephane Rolland
Stephane Rolland

Reputation: 39906

You should use forward class declaration.

//in A.h

    class B; // forward declaration
    class A
    {
    protected:
       B *p;
       friend class B; // forward declaration
    };

//in B.h
class A; // forward declaration
class B
{
protected:
   A *p;
   friend class A; // forward declaration
};

Upvotes: 3

Jón Trausti Arason
Jón Trausti Arason

Reputation: 4698

You could use a forward declaration by doing class B; above class A

Upvotes: 1

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133024

class B;
class A
{
protected:
   B *p;
   friend class B;
};

class B
{
protected:
   A *p;
   friend class A;
};

Upvotes: 1

unquiet mind
unquiet mind

Reputation: 1112

class A
{
protected:
   class B *p;
};

If you want to declare friendship, you need a forward declaration:

class B;

class A
{
friend class B;
protected:
   B *p;
};

Upvotes: 1

kinnou02
kinnou02

Reputation: 654

you must use forward declaration like:

class B;
class A{
   ...
   friend class B;
};

Upvotes: 1

Related Questions