2.2 const data member

In a class definition, a data member (public or private) can be const. This may seen strange, because apparently there is no way to initialize such data members. Let us consider the following example:

class X
{
    const int i;
  public:
    X(void);
};

X::X(void)
{
  i = 2;
}

The above code generates an error because i is a const data member, it cannot be altered! So, what good does a const data member do when its initial value cannot be set?

As it turns out, a const data member can get its initial value from a special mechanism to initialize data members. The following code illustrates this:

X::X(void):i(23)
{
}

This code does not generate any error message. This is because i(23) is considered the initialization of i while i is being defined. It is kind of like const int i = 23.

Also, note that the initializer of i can use any parameter of the constructor itself. Observe the following example:

class X
{
    const int i;
  public:
    X(int x, int y);
};

X::X(int x, int y):i(x+y)
{
}



Copyright © 2006-09-19 by Tak Auyeung