i have searched many sources about initialization lists but i can't find a useful source . can't understand what it is and for what it is used .Can Anybody explain it in details or show me a good source? i read from http://www.cprogramming.com/tutorial/initialization-lists-c++.html
An initialization list is used in the constructor to initialize class members and base classes
eg:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
struct Base
{
int x;
Base ( int y, int z ) : x ( y+z )
{
// list above is the same as x=y+z; but it calls the constructor for x instead of the assignment operator
}
};
struct Derived : public Base
{
double d;
Derived ( int y, double d ) : Base ( x, 5 ), d ( d )
{
// Above calls Base constructor and initializes d
// Notice that the d outside parentheses is the struct member,
// the one inside parentheses is the constructor parameter
}
}
struct Base
{
int x;
Base ( int y, int z ) : x ( y+z )
{
// list above is the same as x=y+z; but it calls the constructor for x instead of the assignment operator
}
};
Base ( int y, int z ) : x ( y+z ) is x a variable or a construction?
and what does "but it calls the constructor for x instead of the assignment operator" mean?
and can you explain the second code with examples.Moreover i have a little information about copy constructors.Could you explain it.Thanks for all your helps:
struct Derived : public Base
{
double d;
Derived ( int y, double d ) : Base ( x, 5 ), d ( d )
{
// Above calls Base constructor and initializes d
// Notice that the d outside parentheses is the struct member,
// the one inside parentheses is the constructor parameter
}
}
#include <iostream>
usingnamespace std;
class C
{
int i;
public:
C() : i ( 0 ) { cout << "Default constructor" << endl; }
C ( int j ) : i ( j ) { cout << "Constructor with value = " << i << endl; }
C ( const C & other ) : i ( other.i ) { cout << "Copy-constructor " << other.i << endl; }
C& operator= ( const C& other )
{
i = other.i;
cout << "Assignment operator " << other.i << endl;
}
C& operator= ( int j )
{
i = j;
cout << "Assignment operator with value = " << j << endl;
}
~C() { cout << "Destructor" << endl; }
};
struct Base
{
C x;
Base ( int y, int z ) : x ( y+z )
{
}
Base ( int y )
{
x = y;
}
};
int main()
{
Base a ( 1,2 ); // calls constructor with initializer list, which calls C constructor
Base b ( 3 ); // calls constructor without initializer list, which calls C assignment operator
}
Try to modify the code above and see if you can understand how these things work