Class Methods

A function that is declared within the body of a class declaration (without the friend specifier being applied) is part of the class. Functions declared in this way are referred to as methods or member functions. Non-static methods have two features which immediately set them apart from non-member functions:

These two properties are related in that the this pointer is the mechanism used to achieve access to the members.

The following applies to methods.


class point
 double x;                                // members x and y are private.
 double y;

  point(double x_set=0, double y_set=0)   // Constructor initializes the members with
   : x(x_set), y(y_set) {}                // the values that are supplied as parameters.
                                          // Parameters have default initializers.
  void set(double x_set, double y_set);   // Method is declared but not defined.
  double operator()(unsigned index) const // constant methods do not update members.
  {return index==0 ? x : y;}              // This method is automatically inlined.
                                          // by virtue of the fact that they are defined within the class.
// Below is the definition of point::set - note how the method name is qualified !
void point::set(double x_set, double y_set) {x = x_set; y = y_set;}
point origin;           // Constructor called - zero values defaulted.
point test(1,2);        // Constructor called - values explicitly specified.
double x = test(0);     // Use operator to access members.
double y = test(1);
test.set(10,20);        // Non-constant method that updates the fields.