You are missing the static keyword.
// .h class Playfield { public: static char GetTile( int x, int y ); // static on a method means no 'this' is involved }; // .cpp static char tiles[10][10] = {}; // static on vars in .cpp prevents access from outside this .cpp char Playfield::GetTile( int x, int y ) { // handle invalid args // return tile return tiles[x][y]; }
Other options if you want only one unique playing field: You can make Playfield single, turn it into a namespace or use global functions. The result will be the same from the perspective of the caller.
On the side of the note: Since they all use a static and / or global variable, they are inherently not thread safe.
If you need several playing fields and / or want to play in safe mode using multithreading and / or want to do it in OOP mode, you will need a Playfield instance to call the function (pointer 'this'):
class Playfield { public: char GetTile( int x, int y ) const { return this->tiles[x][y]; } // you can omit 'this->', but it inherently present because // the method is not marked as static public: Playfield() { /*you will have to initialize 'this->tiles' here because you cannot use the struct initializer '= {}' on member vars*/ } private: char tiles[10][10]; };
The calling code will use Playfield as follows:
void main() {
source share