Why the argument to a copy constructor is passed by reference: If we try to pass the argument by value to a copy constructor (ie, for a class X, if we use an X(X) constructor in place of X(X&), the compiler complaints out of memory. The reason is, when an argument is passed by value, a copy of it is constructed. To create a copy of the object, the copy constructor works. But the copy constructor is creating a copy of the object for itself, thus it calls itself. Again the called copy constructor requires another copy so again it is called.
In fact it calls itself again until the compiler runs out of memory. So, in the copy constructor, the argument must be passed by reference, so that to make a copy of the passed object, original object is directly available.
Dynamic initialization of objects: The dynamic initialization means that the initial values may be provided during runtime. The benefit of dynamic initialization is that itprovides the flexibility of assigning initial values at run time.
Initialization of Const & Reference Members: If your class contains a constant and a reference as member field, then you need to specify that through Member-Initialization List. A constructor can initialize the constituent data members of its class through a mem-initialization list that appears in the function header of the constructor.
Eg:
class Test
{
int a ;
char b;
public:
Test(int i,char j):a(i), b(j);//a(i) initializes member a with
//value i, b(j)….b
with j.
{
….
}
}
You can even have a combination of meminitialization list and initialization within constructor body.
Eg:
class Test
{
……
public:
Test(int i, char j):a(i)
{
b=j;
}
…..
};
And if your class contains a const members must be initialized through meminitialization list as these cannot be initialized within constructor body.
Eg:
struct Sname
{
char fname[25];
char lname[25];
} S1;
class Test
{
int a,b;
const int max; //const member Sname &name; //reference member
public:
Test ( ):max(300),name(S1)
{
a=0;
b=10;
}
------
};
Mem-initialization lists are especially used in the following four cases:
(i) initialization of const members.
(ii) initialization of reference members.
(iii) Invoking base class constructor.
(iv) Initialization of member objects
CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )