Export (0) Print
Expand All

Member Functions (C++)

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:

// member_functions1.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

class Point
{
public:
   short x()
   {
      return _x;
   }
   
   short y()
   {
      return _y;
   }

   void  Show()
   {
      cout << x() << ", " << y() << "\n";
   }
private:
   short _x, _y;
};

int 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).

NoteNote

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 and called:

// member_functions2.cpp
class Point
{
public:
   unsigned GetX()
   {
      return ptX;
   }
   unsigned GetY()
   {
      return ptY;
   }

   void SetX( unsigned x )
   {
      ptX = x;
   }
   void SetY( unsigned y )
   {
      ptY = y;
   }

private:
    unsigned ptX, ptY;
};

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 );
}

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.

Community Additions

ADD
Show:
© 2014 Microsoft