Introduction to Programming and C++

Contents Previous Topic Next Topic

A global function must be declared before it is used, even if it isn't necessarily defined. At a minimum, the declaration of a function includes the return type, the name of the function, and the types of the arguments. This is also called the signature and prototype (there are some subtle differences, but for the most part, they are identical). These indicate to the compiler how the function should be used. Variable names are not required in function declarations. Some examples are:

    double sin( double );
    int floor( double );

A global function which is has the modifier static is only accessible from within the file in which it is defined.

A global function which is has the modifier extern is defined in a another file.

Friends and Global Functions

A function must be declared before it can be used in any statement, including a friend statement. Thus, you will note in the code for Verbose.h that we:

  • Declare the class (so we can use it in the function declaration),
  • Declare the function (so we can use it in the friend statement),
  • State that the function is a friend, and then
  • Define the function.

This is shown here:

template <typename T>
class Verbose;

template <typename T>
ostream & operator << ( ostream &, const Verbose<T> & );

template <typename T>
class Verbose {
	// ...

	friend ostream & operator << <> ( ostream &, const Verbose<T> & );
};

// ...

template <typename T>
ostream & operator << ( ostream & out, const Verbose<T> & v ) {
	out << "#" << v.id << " (= " << (&v) << ")";

	return out;
}

Contents Previous Topic Top Next Topic