Hi,
I was just browsing through some stuff about Initialization lists in C++ and got stuck with a doubt..
Why is it necessary to use initialization lists while giving a value to constants or references ??
Why is it not possible to do so in the normal way..i.e initializing them within the constructor.
Any help would be appreciated..
Thanks in advance..
Classes can contain member objects of class type, but to ensure that initialization requirements for
the member objects are met, one of the following conditions must be met:
The contained object’s class requires no constructor.
The contained object’s class has an accessible default constructor.
The containing class’s constructors all explicitly initialize the contained object.
The following example shows how to perform such an initialization:
// Declare a class CPoint.
class CPoint
{
public:
CPoint( int x, int y ) { _x = x; _y = y; }
private:
int _x, _y;
};
// Declare a CRectangleangle class that contains objects of type CPoint.
class CRectangle
{
public:
CRectangle( int x1, int y1, int x2, int y2 );
private:
CPoint TopLeft, BottomRight;
};
// Define the constructor for class CRectangle. This constructor
// explicitly initializes the objects of type CPoint.
CRectangle::CRectangle( int x1, int y1, int x2, int y2 ) :
TopLeft( x1, y1 ), BottomRight( x2, y2 )
{
}
The CRectangle class, shown in the preceding example, contains two member objects of class CPoint. Its
constructor explicitly initializes the objects TopLeft and BottomRight. Note that a colon follows
the closing parenthesis of the constructor (in the definition). The colon is followed by the member
names and arguments with which to initialize the objects of type CPoint.