Friday, August 19, 2011

Declarations and Definitions

Any identifier must be declared or defined before it is used.
Declaring a name means telling the compiler what type to associate with that name. The location of the declaration determines its scope. Scope is a region of code where an identifier can be used. Defining an object, or variable, means allocating space and (optionally) assigning an initial value. For example,

double x, y, z;
char* p;
int i = 0;
CString message("Hello");

Defining a function means completely describing its behavior in a block of C++ statements. For example,

int max(int a, int b) {
   return a > b ? a : b;

Defining a class means specifying its structure in a sequence of declarations of function and data members.

class CPoint {                          // class definition
      CPoint(int x, int y, int z);      // constructor declaration
      int nDistance(Point other);       // function declaration
      double norm() const {             // declaration and definition
         return nDistance(Point(0,0,0));
      int m_Xcoord, m_Ycoord, m_Zcoord; // data member declaration

Example contains some declarations that are not definitions.

Now consider an example again:

extern int step;       // an object (variable) declaration
class Map;             // class declaration
int max(int a, int b); // global (non-member) function declaration

In each case, there is an implicit promise to the compiler (which will be enforced by the linker) that the declared name will be defined somewhere else in the program. Each definition is a declaration. There can be only one definition of any name in any scope, but there can be multiple declarations.

Variable initialization is optional in C++. Nevertheless, it is strongly recommended that an initial value be provided for all variable definitions, otherwise invalid results or strange runtime errors can occur that are often difficult to locate. It is worth repeating this rule: All objects and variables should be properly initialized at creation time.

No comments:

Post a Comment