C++ Member Functions Bob Walton, 7/16/96 Consider: struct foo { . . . . . int first ( void ) // A function member. { return first_index; } . . . . . int first_index; // A data member. }; int first ( foo & x ) { return x.first_index; } Then two different functions named `first' are defined. One is called called by: foo x = ... ; ... x.first() ... and the other by foo x = ... ; ... first ( &x ) ... The second is just an ordinary function. The first is a `member function'. It is like a data member of the struct, but it is a function and takes arguments like a function. You can declare functions to be members of structs (classes, unions). They are called using the `.' operator, like data members, but are given arguments, like a function. Zero arguments must be represented by `()' in a call to the function. The definition of the member function above may be given inside the struct, or after the struct. In the latter case it is written: int foo::first ( void ) { return first_index; } The code in this definition is in the scope of the `foo class'. You may use names that are defined in this scope without the prefix `foo::'. Inside a member function, the magic identifier `this' denotes a pointer to the object being processed. So in `x.first()' the identifier `this' is a `foo *' pointer to x. You could then write: int foo::first ( void ) { return this->first_index; } which is equivalent to the previous definition. In fact, when you see the name of a member inside a member function, you can prefix it with `this->' to get its true meaning. I.e., when you see `first_index' in the first definition, it really means `this->first_index'. Because data members may be used as variables inside member functions, it is a bad idea to give data members the same names as user defined types. Something you could do in C, but should not in C++. It is possible for a member function to have an argument with the same name as the data member. E.g. struct foo { . . . . . void first ( int first_index ) { this->first_index = first_index; } . . . . . int first_index; } defines a member function that sets the data member first_index. Inside the member function, `first_index' refers to the argument, and `this->first_index' to the data member.