Eko
Eko

Reputation: 1557

Pointer to a child class

I have a class which needs a pointer to a child class :

class A
{
    protected :
        B *pB;
}

class B : public A
{

}

But this is not working.

Upvotes: 1

Views: 99

Answers (3)

Siddhartha Ghosh
Siddhartha Ghosh

Reputation: 3198

Forward declare class B and it should be class B: public A, not the reverse. i.e.

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

class B: public A
{

}

Upvotes: 1

Salgar
Salgar

Reputation: 7775

You need to forward declare B otherwise the compiler doesn't know B exists if it is listened after A.

class B;

class A
{
    protected :
        B *pB;
}

class A : public B
{

}

Upvotes: 3

Claudio
Claudio

Reputation: 10947

Put a forward declaration at the beginning:

class B;

class A
{
    protected :
    B *pB;
}

class A : public B
{

}

Upvotes: 4

Related Questions