1

In a file named maze.hpp (a header file) I have the following:

class Maze
{
    public:
        Maze(int size);
        ~Maze() {}

        void step();

    private:

        int exitRow;    
};

In another file named maze.cpp I have the following:

void step(){

    this.exitRow = 3;

}

int main(){
    Maze maze(4);
    maze.step();
}

This gives an error: invalid use of 'this' outside of a non-static member function

step is a member function of Maze. How can I access the data members of an instance of Maze from within one of its member functions?

R Sahu
  • 204,454
  • 14
  • 159
  • 270
Davido Widre
  • 185
  • 2
  • 13

3 Answers3

3

When you define a function outside of the class declaration, you are required to provide the class name like this:

void Maze::step(){

    exitRow = 3;

}

The compiler has no other way of knowing where the method that you're defining belongs.

Note that there is no need to use this when referring to members from a member function. this is still available and technically writing something like the following is valid: this->exitRow = 3;, but unnecessary. Also, this is a pointer (hence the usage of operator -> rather than .).

nicebyte
  • 1,498
  • 11
  • 21
3

The lines

void step(){    
    this.exitRow = 3;
}

define a global function, not a member function of Maze. Also, this.exitRow is the wrong syntax. You need:

void Maze::step(){
    this->exitRow = 3;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • This seems to uncover a bigger problem. I followed your above suggestion, and now I get: `Undefined symbols for architecture x86_64: "Maze::Maze(int)", referenced from: _main in maze-780529.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)` – Davido Widre Feb 02 '15 at 06:16
  • You've to define `Maze::Maze(int size)` too. You can define it inline by using `Maze(int size) : exitRow(0) {}` or in the .cpp file by using `Maze::Maze(int size) : exitRow(0) {}`. I don't know how `size` is related to `exitRow`. You'll have to figure that out. – R Sahu Feb 02 '15 at 06:22
2

Your function definition should be:

void Maze::step()
{

}

The way it is now, it just defines a free standing function that does not belong to any class.
Also, this is a pointer so you need to access members by dereferencing it using ->. And it is good to note that you do not need to use this->exitRow to refer exitRow, merely mentioning exitRow inside the member function will serve the same purpose.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • This seems to uncover a bigger problem. I am compiling using g++ maze.cpp, but I get `Undefined symbols for architecture x86_64: "Maze::Maze(int)", referenced from: _main in maze-0e50e8.o` Any idea what I can do now? – Davido Widre Feb 02 '15 at 06:20
  • @DavidoWidre: You have not defined the constructor which takes a `int` parameter. you need to define `Maze::Maze(int)`. – Alok Save Feb 02 '15 at 06:24