2.2 C++

Now, let us consider a equivalent C++ class definition and matching constructor member function:

class Y
{
  public:
    int i;
    float f;
    char a[20];

    Y(void);
}

Y::Y(void)
{
  i = 0;
  f = 3.14;
  a[0] = '\0';
}

We'll also include a block of code that has the definition of a variable of type Y:

{
  Y myY;

  cout << myY.i << " " myY.f << " " << myY.a << endl;
}

There is no explicit call to the constructor Y::Y. In C++, the definition of a variable (of a class) automatically calls the constructor member function after storage is allocated. In other words, you can imagine that there is a myY.Y() invocation immediately after the definition of myY.

Consequently, when the data members are printed, we'll get 0, 3.14 and an empty string.



Copyright © 2006-09-05 by Tak Auyeung