It is often seen in programming that variables of different data types are used in the same expressions e.g. float with integer or an integer with a double. In these cases, C++ automatically converts one data type to another as the situation demands. The data type to the right of the assignment operator is converted to the type of data to the left.

For example, when assigning an int to a float, the int will be promoted to a float and then assigned. The type conversions are automatic as long as the data types involved are built-in types.

Like basic data types, the equal to assignment operator can also be used with user defined data types. For example:

.cf { font-family: Lucida Console; font-size: 9pt; color: black; background: white; }
.cl { margin: 0px; }
.cb1 { color: green; }
.cb2 { color: blue; }
.cb3 { color: maroon; }

 

class coordinate
{
private: int x;
 int y;
public:
 Coordinate( int a, int b)
 {
 x=a;
 y=b;
 }
 Coordinate operator+(Coordinate &rhs)
 {
 return Coordinate(x+rhs.x, y+rhs.y);
 }
};

 

Coordinate O1(3.5, 5), O2(4, 6.5), O3; O3 = O1 + O2;

We have defined a class which stores the two coordinates x and y as its data members. In the first statement in main, we have declared 3 objects of type Coordinate.

In the second statement the sum of objects O1 and O2 is assigned to O3. In classes when one object is assigned to another object of the same class, then the value of all the data members are copied into the corresponding data members of the object being assigned to.

Here are three situations when the compiler needs special instructions to use the assignment operator:

  1. Conversion from basic type to class type.
  2. Conversion from class type to basic type.
  3. Conversion from one class type to another class type.