20.1.  Declarations and Definitions

[ fromfile: scopestorage.xml id: iddefdecl ]

Example 20.1. src/early-examples/decldef/point.h

class Point {                           1
 public:
    Point(int x, int y, int z);         2
    int distance(Point other);          3
    double norm() const {               4         
        return distance(Point(0,0,0));
    } 
 private:
    int m_Xcoord, m_Ycoord, m_Zcoord;   5
};

1

Class head.

2

A constructor declaration.

3

A function declaration.

4

Declaration and definition.

5

Data member declaration.


Example 20.2. src/early-examples/decldef/point.cpp

extern int step;       1
class Map;             2
int max(int a, int b); 3

1

An object (variable) declaration.

2

A (forward) class declaration.

3

A global (non member) function declaration.


[Note]Note
  • Variable initialization might seem to be "optional" in C++.

  • But initialization of variables always takes place – regardless of whether it is specified.

  • A statement of the form

    TypeT var;

    results in default initialization of the variable var.

  • Default initialization means that a value is supplied by the compiler.

  • For simple types (e.g., int, double, char) the default value is undefined; i.e., that value might be zero and it might be some random garbage that happens to be in the memory assigned to var.

  • For class objects, the value is determined by the default constructor, if one exists – otherwise the compiler reports an error.

  • Consequently, it is strongly recommended that a well-chosen initial value be provided for all variable definitions;