forward declaration?

M

Michael Sgier

Hello
with the original code below I get the error:
"forward declaration of `struct CPlayer'"

class CPlayer; // what does this do? Instantiate the class CPlayer?
// what's a forward declaration?

class CEnemy : public CEntity
{
public:
CPlayer *player;
}

I tried it like this which brought the error:
"error: syntax error before `*' token"

class CEnemy : public CEntity
{
public:
// CPlayer *player;
CPlayer* player = new CPlayer;
}

THANKS for you help and regards.
Michael
 
D

David White

Michael said:
Hello
with the original code below I get the error:
"forward declaration of `struct CPlayer'"

class CPlayer; // what does this do? Instantiate the class CPlayer?

No. It tells the compiler that CPlayer is a class. This is necessary if you
have classes that refer to each other, or you can do it in some
circumstances simply to avoid #including the header that defines the class,
which can speed up compilation.
// what's a forward declaration?

The declaration for CPlayer above is a forward declaration, i.e., you've
specified it as a class ahead of the full class definition, which will be
somewhere else.
class CEnemy : public CEntity
{
public:
CPlayer *player;
}

Missing semi-colon.

There must be other code that you compiled but did not post. Where is the
definition of CEntity? Also, to get an error for 'struct CPlayer' suggests
that CPlayer is really a struct, not a class. I'm guessing that the source
file you compiled #includes the full definition of CPlayer, which is a
struct, but the forward declaration says it's a class, hence the error
message.

You can use a forward declaration if you only refer to pointers or
references to CPlayer (which is the case here), but you need the entire
definition of CPlayer in other cases, such as defining a member object of
type CPlayer in CEnemy (as opposed to a pointer or reference), or accessing
any member of CPlayer, etc.
I tried it like this which brought the error:
"error: syntax error before `*' token"

Yes, because the compiler does not know what CPlayer is. You need a forward
declaration of CPlayer, the full definition of CPlayer, and you need the
full definitionof CEntity.
class CEnemy : public CEntity
{
public:
// CPlayer *player;
CPlayer* player = new CPlayer;
}

Another missing semi-colon.

DW
 
D

David White

David White said:
Yes, because the compiler does not know what CPlayer is. You need a forward
declaration of CPlayer,

Correction: Insert the word "or" here.
the full definition of CPlayer, and you need the
full definitionof CEntity.

DW
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top