Example of Defining a Member


/************************************************************************
*

The following example defines a member function outside of its class declaration.

                                                                        *
************************************************************************/


// This example illustrates member scope.

#include <iostream.h>
class X
{
public:
      int a, b ;      // public data members
      int add();      // member function declaration only
};
int a  = 10;          // global variable
// define member function outside its class declaration
int X::add() {return a + b;};
//      .
//      .
//      .
void main()
{
    int answer;
    X xobject;
    xobject.a = 1;
    xobject.b = 2;
    answer = xobject.add();
    cout << xobject.a << " + " << xobject.b << " = " << answer;
}


/************************************************************************
*

The output for this example is: 1 + 2 = 3

Note: All member functions are in class scope even if they are defined outside their class declaration. In the above example, the member function add() returns the data member a, not the global variable a.

                                                                        *
************************************************************************/