Thursday 25 April 2013

Member Functions

Member functions are functions that are defined or declared within the body of a class
definition. They form part of the class description. Member functions are normally used to
provide operations on the class data. As they form part of the class definition, each instance
(variable) of the class will have associated with it the operations defined within the class.
By making the functions that modify or read the data contained in the class member
functions we know that any code that sets or reads the data incorrectly must be within the
class itself. This helps debugging and makes it easier to produce abstract data types.
Member functions are also referred to as class methods.
If the code for a member function is defined within the class, then that member function will
be treated as an inline function (see 1.12); more normally the member function is declared
within the class and defined elsewhere. The scope resolution operator, ::, is used to specify
the class to which the function belongs.
An alternative way of defining the print method from the string class shown above
would be:
class string {
private:
char *str;
public:
constructors and destructors
// declare the print method
void print() const;
};
// define the print method
void string::print() const
{
cout << str;
}

1 comment: