You can arrange for the fields in a structure to be initialized
whenever a structure variable is created. This is part of C++, and is
not available in C. Inside the structure type definition,
put a function definition,
without a return type, whose name is the same
as the name of the structure. This function is called a
constructor. For example, suppose that you want each complex
number to initially 0. You can write the complex type as follows.
struct Complex {
double re,im;
Complex()
{
re = 0.0;
im = 0.0;
}
};
Another option is to ask for the initial values when a variable is
created. That can be done by creating a constructor that has
parameters. For example, you might declare the complex number
structure as follows.
struct Complex {
double re,im;
Complex()
{
re = 0.0;
im = 0.0;
}
Complex(double r, double i)
{
re = r;
im = i;
}
};
Now
Complex z, x(1,2);
declares variable z to be initialized by the constructor without
parameters (and hence to have both its real and imaginary parts
initialized to 0) and x to be initialized the the constructor with
parameters (and hence to have a real part initialized to 1.0, and an
imaginary part initialized to 2.0).
|
You must use constructors that are given |
You can provide any number of constructors with a structure
definition. But if you provide any, then one of the constructors
that you provide must be used whenever a new structure is created.
(If you do not provide any constructors, some default constructors
are created for you.)
When you write
Complex c;
without any parameters after c, you are using the constructor with
no parameters. If you provide at least one constructor, but do not
provide a parameterless one, then this is not allowed.
|
Copy constructors and assignment |
There are times when a structure needs to be copied. You can control
how that is done in two ways.
Copy constructor |
A copy constructor for type Complex has the form
Complex(const Complex& c)
{
...
}
It is run inside the copy, with c set to the object that is being copied.
The default one is
Complex(const Complex& c)
{
re = c.re;
im = c.im;
}
but you can define it to work the way you want it to work.
|
Assignment |
You can control how assignment is done by redefining the = operator.
For type Complex, the default = operator is as follows.
Complex& operator=(const Complex& c)
{
re = c.re;
im = c.im;
return *this;
}
but you can redefine how it works. It runs in the structure that
is being set, with c the structure that is being copied. *this is
just the thing that is being set. So the = operator returns the
structure that it changed.
|
|
Creating arrays of structures |
When you create an array of structures, the constructor with
no parameters is automatically run for each thing in the array.
If you do not have a constructor with no parameters, then you
are not allowed to create an array of that kind of structure.
|
|