Thanks for the reply. I understood the difference between Copy Cons and
Assignment Operator. But, I could not make out when should I use copy
constructor and when should I use assignment operator. Can anyone
enlighten me on that?
In general, and even though it may seem counterintuitive, you should
prefer construction over assignment, whenever a choice is available.
For example, consider the numberString variable in the following
routine:
void PrintOneThroughTen()
{
for (int i = 1; i < 11; i ++)
{
std::string numberString( std::atoi( i ));
std::cout << numberString << ", ";
}
}
and in this implementation:
void PrintOneThroughTen()
{
std::string numberString;
for (int i = 1; i < 11; i ++)
{
numberString = std::atoi( i );
std::cout << numberString << ", ";
}
}
The first implementation constructs numberString while the second
assigns it a value each time through the loop. Both examples are
correct, but the first one by using construction is the more efficient
implementation than the second one which uses assignment to ensure that
numberString has the intended value.
The explanation for this rule of thumb (construction instead of
assignment) is left as an assignment to the reader to provide.
Greg