Zak Kousens Zak Kousens - 13 days ago 8
C++ Question

Function 'not declared in this scope' when using class in C++

I'm trying to make a basic program that allows users to play each other in othello, and right now I'm just trying to initialize a blank array that represents the board and display it. I've worked with classes a few times, and my code doesn't seem to be any different from the other classes I've made, but I can't find why my functions aren't properly declared. The errors are:

othello.cpp: In function ‘int main()’:
othello.cpp:9:17: error: ‘generateBoard’ was not declared in this scope
generateBoard();
^
othello.cpp:10:13: error: ‘addBorder’ was not declared in this scope
addBorder();
^
othello.cpp:11:18: error: ‘displayOthello’ was not declared in this
scope
displayOthello();
^
make: *** [othello.o] Error 1


Here is othelloboard.h

const int boardSize = 4;

class othelloboard{
public:
othelloboard();
~othelloboard();
void generateBoard();
void addBorder();
void displayOthello();

private:
char othelloArray[boardSize][boardSize];
};


Here is othelloboard.cpp

#include <iostream>
using namespace std;

#include "othelloboard.h"

//Initialize global variables
extern const int boardSize;

othelloboard::othelloboard(){}
othelloboard::~othelloboard(){}

void othelloboard::generateBoard(){
for (int i=1; i<= boardSize; i++){
for (int j=1; j<= boardSize; j++){
othelloArray[i][j] = '.';
}
}
}

void othelloboard::addBorder(){
for (int i=1; i<= boardSize; i++){
char temp = (char)i + '0';
othelloArray[0][i] = temp;
othelloArray[i][0] = temp;
}
}

void othelloboard::displayOthello(){
for (int i=0; i<= boardSize; i++){
for (int j=0; j<= boardSize; j++){
cout << othelloArray[i][j];
}
cout << endl;
}
}


Here is Othello.cpp

#include <iostream>
using namespace std;

#include "othelloboard.h"

int main(){
extern const int boardSize;
cout << boardSize << endl;
generateBoard();
addBorder();
displayOthello();
}


I also know global variables aren't the greatest, but we were instructed to use a global variable for board size. Thank you for the help.

Answer

In order to be able to call the methods implemented in othelloboard.cpp, you have to create an object of type othelloboard inside main(), then you can simply call the methods using objectName.methodName(). Basically you have to do the following:

  1. Create the object of type othelloboard:

    othelloboard ob;

  2. Call your methods using

    ob.generateBoard();

etc