Defining Member Functions

Defining Member Functions
Defining Member Functions
CONCEPT

Class member functions can be defined either inside or outside the class declaration.

EXPLANATION

Class member functions are defined similarly to regular functions. Except for a few special cases we will look at later, they have a function header that includes a return type (which may be void), a function name, and a parameter list (which may possibly be empty). The statements that carry out the actions of the function are contained within a pair of braces that follow the function header.
So far, all the class functions we have written have been defined within the class declaration itself. When a class function is defined in this location, it is called an inline function. Inline functions provide a convenient way to contain function information within a class declaration, but they can only be used when a function body is very short, usually a single line. When a function body is longer, a prototype for the function should appear in the class declaration, instead of the function definition itself. The function definition is then placed outside the class declaration, either following it or in a separate file.
Even though the two functions in our Circle class are short enough to be written as inline functions, we will rewrite them as regular functions, defined outside the class declaration, to illustrate how this is done. Inside the class declaration the functions would be replaced by the following prototypes:

void setRadius(double);
double getArea();
Following the class declaration we would place a function implementation section containing
the following function definitions:

void Circle::setRadius(double r)
{ radius = r;
}
double Circle::getArea()
{
return 3.14 * pow(radius, 2);
}
Notice that these look like ordinary functions except they contain the class name and a double colon (::) between the function return type and function name. The :: symbol is called the scope resolution operator. It is needed to indicate that these are class member functions and to tell the compiler which class they belong to.

WARNING!
The class name and scope resolution operator are an extension of the function name. When a function is defined outside the class declaration, these must be present and must be located immediately before the function name in the function header.

Here are some additional examples to illustrate how the scope resolution is used when a
class function is defined outside the class declaration.
double getArea() // Wrong! The class name and scope
// resolution operator are missing.
Circle::double getArea() // Wrong! The class name and scope
// resolution operator are misplaced.
double Circle::getArea() // Correct!
Previous
Next Post »