Ostap Maliuvanchuk
Ostap Maliuvanchuk

Reputation: 1175

C++ undeclared identifier

I want to create a sea ​​battle game. I have two classes: Ship and Cell.

#pragma once
#include"stdafx.h"
#include"Globals.h"
#include<vector>
#include"MCell.h"

 class Ship 
 {

 private:
    int lenght;
    int oriantation;
    vector<Cell*> cells;
    vector<Cell*> aroundCells;

...

#pragma once
#include<vector>
#include"MShip.h"

 class Cell
{

private:
    bool haveShip;
    bool selected;
    bool around;
    int x;
    int y;
    Ship* ship; 

And i have got many error like those:

1>projects\seewar\seewar\mship.h(13): error C2065: 'Cell' : undeclared identifier
1>projects\seewar\seewar\mship.h(13): error C2059: syntax error : '>'
1>projects\seewar\seewar\mship.h(14): error C2065: 'Cell' : undeclared identifier

What's wrong with the code?

Upvotes: 3

Views: 6333

Answers (3)

Goz
Goz

Reputation: 62323

Well your problem lies that when you include MCell.h you include MShip.h which references Cell defined in MCell.h. However MShip.h refers to MCell.h which won't get included because of the pragma once. If the pragma once wasn't there then you'd get an inifinite loop that would stack overflow your compiler ...

Instead you could use a forward declaration.

ie remove the #include "MCell.h" from MShip.h and replace it with, simply, "class Cell;" All your circular references issues will this go away :)

Upvotes: 5

Luchian Grigore
Luchian Grigore

Reputation: 258548

You need to forward declare the classes.

Ship.h

class Cell; //forward declaration
class Ship 
{
   //....
};

Cell.h

class Ship; //forward declaration
class Cell
{
   //....
};

and remove the circular inclusion. You don't need to include one header in another since you're not working with complete types, but pointers. Full class definition is required when you use concrete objects of the type. In the case of pointers, you don't.

Upvotes: 1

sepp2k
sepp2k

Reputation: 370092

Your header files depend on each other. However one of them will have to be read before the other. So you need to rewrite one of them (or both of them) to not depend on the other. You can do that by forward-declaring the classes instead of including the header file that defines them.

So in MShip.h you should put a declaration class Cell; instead of including MCell.h and/or vice versa.

Upvotes: 1

Related Questions