Operator overloading and copy constructor relation

In C++ a powerful feature to use is operator overloading.
Operator overloading can be applied to unary, binary and ternary operators. There are some simple rules to follow;
  1. -nary of the operators cannot be changed.
  2. At least one operands should be in user defined class type.
  3. Left hand side of the binary operator should be user defined structure.

I give examples of operator overloading on a class which has properties as ;

float funds,
int noOfPayMonths;
int* payMonths;

and call it as Account class.

// Postfix version.


float Account::operator++(int pDummy)
{
float tmpFunds = funds;
funds++;
return tmpFunds;
}

// Prefix version.
float Account::operator++()
{
return (funds += 1);
}

// Assignment operator.
Account Account::operator=(const Account& pAccountAssignFrom)
{
if(this == &pAccountAssignFrom)
{ // Trying to assign 2 same object to each other.
return *this;
}
else
{
if(noOfPayMonths != pAccountAssignFrom.noOfPayMonths)
{ // The number of pay months are different return NULL.
return NULL;
}
else
{ /* Since this is an assignment operator, we know that the left hand
side of the operator is initialized before the call. Therefore we do
not need to create the pointer variable again as we do in copy
constructors(which you initialize the left hand side).
*/
funds = pAccountAssignFrom.funds;
noOfPayMonths = pAccountAssignFrom.noOfPayMonths;

for(int i = 0; i < noOfPayMonths; i++)
{
payMonths[i] = pAccountAssignFrom.payMonths[i];
}
}
}
}

Copy constructors are background heros which comes front when a variable is passed by value as an argument or being returned in a return statement of functions. We need to create our own copy constructor in order to handle pointer variables to avoid shallow copy while we are thinking that the copy is a deep one.(as we passed it as value!!)

I give an example of a copy constructor for the same class.

// Copy constructor.
Account::Account(const Account& pAccountCopyFrom)
{
// Built-in types are also needed to be assigned because the default copy
// constructor is overridden.
funds = pAccountCopyFrom.funds;
noOfPayMonths = pAccountCopyFrom.noOfPayMonths;

// Since copy constructor is being called on initialization we need to assign
// the pointer values to new dynamic location otherwise a shallow copy will be
// applied by default.
payMonths = new int[noOfPayMonths](); // new contiguous memory allocated.
for(int i = 0; i < noOfPayMonths; i++)
{
payMonths[i] = pAccountCopyFrom.payMonths[i];
}
printf("Copy constructor is called");
}

The idea that I find is copy constructors are being called on initializations whereas an assignment operator is used while assigning variables.

For instance,

int a = getA(); is an initialization and

int c = 3; c = b; is an assignment.

Comments

Popular posts from this blog

Space Character Problem on IE 6, 7, and 8

AWS encryption chart (SSE-S3 vs SSE-KMS vs SSE-C)

Does Netflix work on iOS 5 Beta 4?