Draco
Draco

Reputation: 16374

Why won't this c++ code compile?

Seeig that i'm new to C++ I thought i'd try and write a very simple console app that populates a 2D-array and displays its contents.

But the code I've written won't compile.

Some of the errors I get are:

error C2065: 'box' : undeclared identifier
error C2228: left of '.GenerateBox' must have class/struct/union

Here is my code:

#include <iostream>
using namespace std;

int main()
{
  Box box;
  box.GenerateBox();
}

class Box
{
private:
  static int const maxWidth = 135;
  static int const maxHeight = 60; 
  char arrTest[maxWidth][maxHeight];

public:
    void GenerateBox()
    {
      for (int i=0; i<maxHeight; i++)
        for (int k=0; k<maxWidth; k++)
        {
          arrTest[i][k] = 'x';
        }

      for (int i=0; i<maxHeight; i++)
      {
        for (int k=0; k<maxWidth; k++)
        {
          cout << arrTest[i][k];
        }
           cout << "\n";
      }
    }
};

Any idea whats causing these errors?

Upvotes: 4

Views: 317

Answers (5)

Nikko
Nikko

Reputation: 4252

You have to define Box before using it. So for your small test you can put your class definition before the main.

For bigger programs, you will put your class definitions inside .h header files that you will include at the top of your source files.

Upvotes: 5

Ravi Kumar Singh
Ravi Kumar Singh

Reputation: 187

Is due to pre declaration of main(). Use main after declaration of class Box.

Upvotes: 2

EboMike
EboMike

Reputation: 77762

Move the main function to the bottom of your code. Specifically, you need to define Box before you reference it.

The only time when you can get away with only a forward declaration (i.e. class Box;) is when you just use Box as a pointer or reference.

Upvotes: 6

Dr Deo
Dr Deo

Reputation: 4848

@nikko is right. You have to declare the Box class before using it.By either

  • cutting pasting the declaration
  • or telling the compiler you will declare them later

try this

extern class Box;
//use box class here
//then define it later as you wish

Upvotes: 0

Karl Knechtel
Karl Knechtel

Reputation: 61643

The C++ compiler reads source files in a single pass, from top to bottom. You have described the Box class at the bottom, after main(), after the part where you attempt to use the class. Accordingly, when the compiler gets to the part where you say 'Box box;', it has not yet seen the class definition, and thus has no idea what 'Box' means.

Upvotes: 8

Related Questions