1

I am writing a C++ Tic Tac Toe game, and this is what I have so far:

#include <iostream>
using namespace std;

int main()
{
    board *b;
    b->draw();
    return 0;
}
class board
{
    void draw()
    {
        for(int i = 0; i < 3;++i){
            cout<<"[ ][ ][ ]"<<endl;
        }
    }

};

However, when I created the pointer to board, CodeBlocks gave me an error: 'board' was not declared in this scope. How do I fix this? I am a new C++ programmer.

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75

2 Answers2

4

You have at least the following issues ongoing:

  • You do not initialize the heap object before trying to access it. In this simple scenario, I would suggest a stack object instead of heap.

  • You do not have the board type known before instantiating it on the heap. Just move the board class declaration before the main function or forward declare it. In this simple case, I would just go with the "proper ordering".

  • The draw method is private since that is the default "visibility" in a class. You will need to mark it public. Alternatively, you could switch to struct instead of class to have the board method available as the default "visibility" is public in a struct.

This should fix your code:

#include <iostream>
using namespace std;

class board
{
public:
    void draw()
    {
        for(int i = 0; i < 3;++i){
            cout<<"[ ][ ][ ]"<<endl;
        }
    }

};

int main()
{
    board b;
    b.draw();
    return 0;
}
László Papp
  • 51,870
  • 39
  • 111
  • 135
0

You Should declare board class before main as at object creation time it don't know board class. and after that also code will crash because board* b will only make pointer which can point to board object, so need to change code as -

  #include <iostream>
  using namespace std;

class board
{  
 public :
 void draw()
  {
        for(int i = 0; i < 3;++i)
            cout<<"[ ][ ][ ]"<<endl;
  }
};
int main()
{
    board *b = new board();
    b->draw();
    if(b)
      delete b;
    b=0;
    return 0;
}
DesignIsLife
  • 510
  • 5
  • 11
  • Memory allocation without delete? It is true that the OS might free it up not to leak, but this is not a good example to show in general. Also, please fix your grammar and indentation. – László Papp Apr 20 '14 at 17:00
  • @Laszlo - yes!! But i just want to show that how to make objects by dynamic memory allocation. – DesignIsLife Apr 20 '14 at 17:06
  • Still, your code was wrong, and even now, you seem to think delete cannot work on null pointers. Moreover, it cannot even be null here... – László Papp Apr 21 '14 at 05:14
  • You are getting it wrong man.. Example is showing how to allocate and deallocate memory only. – DesignIsLife Apr 21 '14 at 05:17