8.4 Member Functions

Classes can contain data and functions. These functions are referred to as “member functions.” Any nonstatic function declared inside a class declaration is considered a member function and is called using the member-selection operators (. and –>). When calling member functions from other member functions of the same class, the object and member-selection operator can be omitted. For example:

class Point

{

public:

short x() { return _x; }

short y() { return _y; }

void Show() { cout << “(” << x() << “, ” << y() << “\n”; }

private:

short _x, _y;

};

void main()

{

Point pt;

pt.Show();

}

Note that in the member function, Show, calls to the other member functions, x and y, are made without member-selection operators. These calls implicitly mean this->x() and this->y(). However, in main, the member function, Show, must be selected using the object pt and the member-selection operator (.).

Static functions declared inside a class can be called using the member-selection operators or by specifying the fully qualified function name (including the class name).

Note:

A function declared using the friend keyword is not considered a member of the class in which it is declared a friend (although it can be a member of another class). A friend declaration controls the access a nonmember function has to class data.

The following class declaration shows how member functions are declared:

class Point

{

public:

unsigned GetX();

unsigned GetY();

unsigned SetX( unsigned x );

unsigned SetY( unsigned y );

private:

unsigned ptX, ptY;

};

In the preceding class declaration, four functions are declared: GetX, GetY, SetX, and SetY. The next example shows how such functions are called in a program:

int main()

{

// Declare a new object of type Point.

Point ptOrigin;

// Member function calls use the . member-selection operator.

ptOrigin.SetX( 0 );

ptOrigin.SetY( 0 );

// Declare a pointer to an object of type Point.

Point *pptCurrent = new Point;

// Member function calls use the -> member-selection operator.

pptCurrent->SetX( ptOrigin.GetX() + 10 );

pptCurrent->SetY( ptOrigin.GetY() + 10 );

return 0;

}

In the preceding code, the member functions of the object ptOrigin are called using the member-selection operator (.). However, the member functions of the object pointed to by pptCurrent are called using the –> member-selection operator.