You are on page 1of 71

OPERATOR OVERLOADING

• The term operator overloading means giving the C++ operators


such as ( -, +, --, ++, *, /, >, <, >=, <= etc.) , additional meanings
while applying on user-defined data types.

• For example, the statement:


z=x+y;
can be applied only to basic data-types such as float, int, double,
long etc.

• But consider a case where x, y and z are objects of a user-defined


class. In this case, the above statement is not legal.
• However, by making use of operator overloading, the above
statement can be made legal.

• Operator overloading provides a flexibility to create new definitions


for most of the C++ operators.

• By using classes to create new variables and operator overloading


to create definitions for operators, one can create a new language of
one’s own design.
The users can redefine the meaning of the
following operators.

+ - * / % ^ & |
~
! = < > += -= /=
*= %=
^= &= |= << >> >= <=
== !=
>>= <<= && || ++ -- ->* ,
->
[] () new new[] delete delete[]
The users can’t redefine the following
operators.

:: ( scope resolution operator )


. ( member selection )
.* ( member selection through pointer to
function )
sizeof ( size of operator )
?: ( conditional operator )
Overloading Unary Operator:

• Unary operators act on only one operand.

• Some commonly used unary operators are unary minus (-),


increment (++) and decrement (--) operators.

• Let us start by overloading the unary minus operator.

• The unary minus operator changes the sign of an operand


when applied to basic data-type ( int, float, double etc. ).

• The following program, demonstrates how to overload this


operator so that it can be applied to an object in much the
same way as is applied to an int or float type variable.
Program
//****This program illustrates the overloading of unary munus ( - ) operator******
#include<iostream.h>
class Minus
{
private:
int a, b, c ;
public:
Minus( ) // Default Constructor
{
}
Minus(int A, int B, int C)
{
a=A;
b=B;
c=C;
}
void display(void);
//********Declaration of the operator function**********
void operator - ( );
}; // End of the Class Definition
Cont.
//***********Member Function Definitions*************
inline void Minus :: display(void)
{
cout << "\t a = " << a << endl ;
cout << "\t b = " << b << endl ;
cout << "\t c = " << c << endl ;
}
//*********Definition of the operator function***********
inline void Minus :: operator - ( )
{
a = -a ;
b = -b ;
c = -c ;
}
//*************Main Function Definition***************
void main(void)
{
Minus M(5, 10, -15) ;
cout << "\n Before activating the operator - ( )\n" ;
M.display( ) ;
-M ;
cout << "\n After activating the operator - ( )\n" ;
M.display( ) ;
}
Output:
Operator Function
• To overload an operator, a special function called operator function is used.

• The general syntax of an operator function is:

return_type class_name :: operator operator_type( agruments )


{
Body of the function
}

• Here, return_type is the type of the value returned by the specified operation.

• The keyword operator is used to overload the specified operator

• operator_type is the operator which has to be overloaded.

• The combination of the keyword operator and the operator_type i.e. operator
operator_type represents the name of the function.

• For example, in the above program the declarative of the operator function is given
as:

• void operator – ( ) ;
Cont.
• This declarative tells the compiler to call this member function, whenever the –
operator is encountered, provided the operand is of type Minus.

• In the main( ) function of this program, the object M of type Minus is declared
and initialized to ( 5, 10, -15 ) as:
Minus M( 5, 10, -15 ) ;
• Before activating the operator function, the values of a, b and c are displayed
as:
a = 5
b = 10
c = -15

• After the statement

-M;

the operator function gets activated and the values of a, b and c are displayed
as:

a = -5
b = -10
c = 15
Cont.
• In the above program, the function operator – ( )
takes no argument.

• This function is a member function, and the


member functions can directly access the
members of an object for which they have been
called.

• Therefore, the operator function for overloading the


unary minus operator ( - ) does not require any
argument.
Operator Function with return value
• The operator – ( ) function defined in the above program has a problem. If one
wants to use a statement such as:

M2 = -M1 ;

• in the main( ), the compiler will complain! The reason is that the operator
function operator – ( ) has been defined to have a return type of void, while the
assignment statement is being asked to return a variable of type Minus. Thus,
the statements such as

M2 = -M1 ;

in the main( ) can be made available by following definition of the operator


function:
Minus operator – ( )
{
Minus temp ;
temp.a = -a ;
temp.b = -b ;
temp.c = -c ;
return temp ;
}
program
/* This program illustrates the overloading of the unary minus (-) operator.
The operator function in this program uses a return value. */
#include<iostream.h>
//******Class Definition********
class Minus
{
private:
int a, b, c ;
public:
//**********Member Functions***************
Minus( ) // Default Constructor
{ }
Minus(int A, int B, int C)
{ a=A; b=B; c=C; }
void display(void)
{
cout << "\t a = " << a << endl ;
cout << "\t b = " << b << endl ;
cout << "\t c = " << c << endl ;
}
Cont.
//********Operator Function Definition *******
Minus operator - (void) // Declarative with the return type Minus
{
Minus temp ;
temp.a = -a ;
temp.b = -b ;
temp.c = -c ;
return temp ;
}
} ; // End of the class definition

//*******Main Functiion************
void main(void)
{
Minus M1(5, 10, -15); // Initialization of the object M1 of type Minus
cout << "\n Before activating the operator -( ):\n" ;
M1.display( ) ;
Minus M2 ; // Definining the object M2 of type Minus
M2 = -M1 ; // Activates the function operator -( ) and
// assigns the value of -M1 to M2
cout << "\n After activating the operator -( ):\n" ;
M2.display( ) ;
}
Output:
Cont.
• In the above program, the operator – ( ) function creates a new object,
named as temp of type Minus, for returning the values.

• This type of object is known as temporary object. The values of the


member data i.e. a, b and c are assigned to this temporary object temp as:

temp.a = -a ;
temp.b = -b ;
temp.c = -c ;

• Finally, the function returns the object temp as:

return temp ;

• Thus, the statement like

M2 = -M1 ;

• can be used in the main( ) function.


Overloading the increment operator ( ++ )
#include<iostream.h>
class Increment
{
private:
int count ;
public:
//*****Member Function Definitions******
Increment( ) // Default Constructor
{ count = 0 ; }
Increment(int C) // Constructor with Argument
{ count = C ; }
Increment operator ++ ( ) // Operator Function Definition
{
count++ ;
return Increment(count);
}
void display(void) // Function for displaying the output
{
cout << count << endl ;
}
}; // End of the class definition
Cont.
void main(void)
{
Increment I1, I2(5), I3, I4 ;
cout << "\n Before activating the operator ++( )\n" ;
cout << " I1 = " ;
I1.display( );
cout << " I2 = " ;
I2.display( );
++I1 ; // I1 and I2 are incremented
I2++ ;
cout << "\n After activating the operator ++( )\n" ;
cout << " I1 = " ;
I1.display( );
cout << " I2 = " ;
I2.display( ) ;
I3 = ++I1 ; /* Here, the objects I1 and I2 are incremented again and
their
I4 = I2++ ; values are assigned to the objects I3 and I4 respectively
*/
cout << " I3 = " ;
I3.display( ) ;
cout << " I4 = " ;
I4.display( ) ;
}
Output:
Cont.
• In the above program, when the increment operator ++ is overloaded
using the function operator ++ ( ) there is no distinction between prefix
and postfix notation. That is why all the statements

I1++ ;
++I2 ;
and
I3 = I1++ ;
I4 = ++I2 ;

have the same effect i.e. they are incremented using the prefix notation
only.

• In order to make both notations of the increment operator (prefix &


postfix) to work, the programmer must define two separate functions
as:

operator ++ ( ) // For prefix

operator ++ ( int ) // For postfix


Cont.
• The operator function for overloading postfix increment
operator uses a dummy argument int, which is
automatically set to 0 by the postfix operator ++.

• This dummy argument allows the compiler to distinguish


the two forms (prefix, postfix) of the increment operator.

• In reality it is not an argument and it does not mean an


integer.

• It is simply a signal to the compiler to create the postfix


notation of the operator.
Program: This program demonstrates the overloading of the increment
operator (++), both in the Prefix notation as well as in the Prefix notation
#include<iostream.h>
class Pre_post_incr
{
int count ;
public:
Pre_post_incr( ) // Default Constructor
{ count = 0 ; }
// Continued from the previous page
Pre_post_incr( int c) // Constructor with an argument
{ count = c ; }
Pre_post_incr operator ++ ( ) // Operator Function for overloading the
{ // increment operator in prefix notation
return Pre_post_incr(++count);
}
Pre_post_incr operator ++ (int) // Operator Function for overloading the
{ // increment operator in postfix notation
return Pre_post_incr(count++);
}
void display(void) // Function for displaying the output
{ cout << count << endl ; }
}; // End of the class definition
Cont.
//*******Main Function************
void main(void)
{
Pre_post_incr I1, I2, I3, I4 ; // Object declaration of class Pre_post_incr
cout << "\n Before activating the functions operator++() and operator ++ ( int)" ;
cout << " \n I1 = " ;
I1.display( ) ;
cout << " I2 = " ;
I2.display( ) ;
cout << "\n After activating the functions operator++() and operator ++ ( int )" ;
I3 = ++I1 ; // Prefix incrementation
cout << "\n I3 = ++I1 = " ;
I3.display( ) ;
I4 = I2++ ; // Postfix incrementation
cout << " I4 = I2++ = " ;
I4.display( ) ;
}
Output:
Overloading binary operators:
// This program illustrates the overloading of the binary operators + and -
#include<iostream.h>
class complex
{
float real, imaginary ;
public:
complex( ) // Default Constructor without arguments
{ real = 0.0; imaginary = 0.0; }
complex(float r, float i) // Constructor with arguments
{
real = r ;
imaginary = i ;
}
void enterdata(void)
{
cout << "\n Enter the real part of the second complex number: ” ;
cin >> real ;
cout << "\n Enter the imaginary part of the second complex /
number: " ;
cin >> imaginary ;
}
Cont.
void display(void)
{
if (imaginary >=0)
cout << real << "+" << imaginary << " i" << endl ;
else
cout << real << imaginary << " i" << endl ;
}
// Operator Function Definition for overloading the binary operator +
complex operator + (complex C)
{
complex temp ;
temp.real = real + c.real ;
temp.imaginary = imaginary + c.imaginary ;
return temp ;
}
// Operator Function Definition for overloading the binary operator -
complex operator - (complex C)
{
complex temp ;
temp.real = real – c.real ;
temp.imaginary = imaginary – c.imaginary ;
return temp ;
}
} ; // End of the class definition
Cont.
//*************Main Function********************
void main(void)
{
complex c1(2.5, 4.5), c2 ; // Object Definitions
cout << "\n The first complex number i.e. c1 is: " ;
c1.display( ) ; // Displays the first complex number
c2.enterdata( ) ;
cout << "\n The second complex number i.e. c2 is: " ;
c2.display( ) ; // Displays the second complex number
complex c3 = c1 + c2 ;
cout << "\n The sum of two complex numbers i.e. c1 and c2 is:
";
c3.display( ); // Displays the third complex number
complex c4 = c1 - c2 ;
cout << "\The substraction of the complex numbers, c2 from c1 is: " ;
c4.display( ); // Displays the fourth complex number
}
Output:
The definitions of the functions for overloading +
and – binary operators are given as:
complex operator + ( complex c )
{
complex temp ;
temp.real = real + c.real ;
temp.imaginary = imaginary + c.imaginary ;
return temp ;
}
complex operator – ( complex c )
{
complex temp ;
temp.real = real – c.real ;
temp.imaginary = imaginary – c.imaginary ;
return temp ;
}
Cont.
• These two operator functions add and subtract two
complex numbers and return the resultant complex
values respectively.
• Notice that both these functions receive only one
value as argument.
• Now a question arises that from where the other
value comes.
• Let us look at the statements that invoke the
operator functions:
c3 = c1 + c2 ; // Invokes operator + ( ) function
c4 = c1 – c2 ; // Invokes operator – ( ) function
Cont.
• It has been discussed that an object of the same class can invoke a member
function.

• In above statement, the object c1 takes the responsibility of invoking the


function and c2 plays the role of an argument that is passed to the function.

• The above invocation statements are equivalent to:


c3 = c1.operator + ( c2 ) ; // Usual function call syntax
c4 = c1.operator – ( c2 ) ;

• Thus in the functions, operator + ( ) and operator – ( ), the data members of c1


are accessed directly and the data members of c2 (that is passed as an
argument) are accessed using the dot operator (.).

• Thus, both the objects are available for the function. For example, in the
statement:

temp.real = real + c.real ;

real refers to the object c1 and c.real refers to the object c2. temp.real is the
real part of the complex that has been created to hold the result of addition of
c1 and c2.
Nameless temporary object:
• One can avoid the creation of the object temp by replacing
the entire function body by the following statement:

complex operator + ( complex c )


{
return complex ( ( real + c.real ), ( imaginary +
c.imaginary ) ) ;
} // Invokes the second constructor

complex operator – ( complex c )


{
return complex ( ( real – c.real ), ( imaginary - c.imaginary ) )
;
}
Cont.
• When the compiler comes across a statement like this, it invokes an
appropriate constructor, initializes an object with no name and returns
the contents for copying into an object.

• Such an object is called as nameless temporary object and goes out


of the space as soon as the contents are assigned to another object.

• But remember that this statement requires a constructor that takes two
arguments.

• For this purpose, a constructor is already defined in the class definition


as:
complex ( float r, float i )
{
real = r ;
imaginary = i ;
}

• Using nameless temporary objects can make the code shorter, more
efficient and better to read.
Program:
// This program illustrates the overloading of the binary operators + and -
#include<iostream.h>
class complex
{
private:
float real, imaginary ;
public:
complex( ) // Default Constructor without arguments
{ }
complex(float r, float i) // Constructor with arguments
{
real = r ;
imaginary = i ;
}
void enterdata(void)
{
cout << "\n Enter the real part of the second complex number: ” ;
cin >> real ;
cout << "\n Enter the imaginary part of the second complex number:
";
cin >> imaginary ;
}
Cont.
void display(void)
{
if (imaginary >= 0)
cout << real << "+" << imaginary << " i" << endl ;
else
cout << real << imaginary << " i" << endl ;
}
// Operator Function Definition for overloading the binary operator +
complex operator + (complex C)
{
return complex( (real + C.real), (imaginary + C.imaginary) ) ;
}

// Operator Function Definition for overloading the binary operator -


complex operator - (complex C)
{
return complex( (real - C.real), (imaginary - C.imaginary) ) ;
}
}; // End of the class definition
Cont.
void main(void)
{
complex c1(2.5, 4.5), c2 ; // Object Definitions

cout << "\n The first complex number i.e. c1 is: " ;
c1.display( ) ; // Displays the first complex number

c2.enterdata( ) ;
cout << "\n The second complex number i.e. c2 is: " ;
c2.display( ) ; // Displays the second complex number continued
complex c3 = c1 + c2 ;
cout << "\n The sum of two complex numbers i.e. c1 and c2 is: " ;
c3.display( ); // Displays the third complex number
complex c4 = c1 - c2 ;
cout << "\The subtraction of the complex numbers, c2 from c1 is: " ;
c4.display( ); // Displays the fourth complex number
}
Output:
Overloading arithmetic assignment operators:
// This program illustrates the overloading of arithmetic assignment operator
#include<iostream.h>
class Arith_asign
{
private:
int num ;
public:
Arith_asign( )
{ }
Arith_asign(int n)
{ num = n ; }
void Enter(void)
{
cout << "\n Enter the number: " ; cin >> num ;
}
void Display(void)
{
cout << num << endl;
}
Cont.
// Operator function definitions
void operator += (Arith_asign& a)
{
cout << "\n The function operator += is invoked: " ;
num += a.num ;
}

void operator *= (Arith_asign& a)


{
cout << "\n The function operator *= is invoked: " ;
num *= a.num ;
}

void operator - = (Arith_asign& a)


{
cout << "\n The function operator -= is invoked: " ;
num -= a.num ;
}
}; // End of the class definition
Cont.
void main(void)
{
Arith_asign A1(10), A2;
cout << "\n The value of data in the object A1 is: " ;
A1.Display( ) ;
A2.Enter( );
cout << "\n The value of data in the object A2 is: " ;
A2.Display( ) ;
A1 += A2 ;
cout << "\n The value of data of object A1 = " ;
A1.Display( ) ;
A1 *= A2 ;
cout << "\n The value of data of object A1 = " ;
A1.Display( );
A1 -= A2 ;
cout << "\n The value of data of object A1 = " ;
A1.Display( );
}
Output:
Overloading the relational operators: This program illustrates the
overloading of conditional operators > and ==
#include<iostream.h>
class Time
{
float hour, minute, second;
public:
void enter_time(void)
{
cout << "\n Enter the time in Hours, Minutes & seconds
";
cin >> hour >> minute >> second ;
}
void display_time(void)
{
if(second >=60)
{ minute = minute+1 ; second = second-60 ; }
if(minute >= 60)
{ hour = hour+1 ; minute = minute - 60; }
cout << hour << " Hours " << minute << " Minutes "
<< second << " seconds " << endl ;
}
Cont.

int operator > (Time& t) // Opetator Function for overloading > operator
{
if(hour > t.hour)
return 1 ;
else
return 0 ;
}

int operator == (Time& t) // Operator Function for overloading == operator


{
if(hour==t.hour && minute==t.minute && second==t.second)
return 1 ;
else
return 0 ;
}

} ; // End of the class definition


Cont.
void main(void)
{
Time time1, time2 ;
time1.enter_time( ) ;
cout << "\n time1 = " ;
time1.display_time( );
time2.enter_time( );
cout << "\n time2 = " ;
time2.display_time( );
if(time1 > time2) // Invokes the function operator > (Time& t)
cout << "\n time1 is greater than time2" ;
else if (time1==time2) // Invokes the function operator == (Time& t)
cout << "\n time1 and time2 are equal" ;
else
cout << "\n time1 is less than time2" ;
}
Output:
First run:

Second run:
Points to remember:

• 1. While overloading the binary operator, left


hand operand is used to invoke the operator
function and the right-hand operand is passed
as an argument.

• 2. An overloaded operator always requires


one less argument than its number of operands,
since one operand is the object of which the
operator is the member function. That’s why
unary operators require no argument.
Data Conversion:
Data Conversion between same data-types ( basic or user
defined ):
• We know that the assignment operator (=) assigns a value
from one variable to another. For example, consider the
following statements:
int x, y ;
int x = y ;
• In the first statement, the integer type variables x and y are
declared. The second statement indicates that the value of y
is assigned to x, using the = operator.
• The = operator was also used in the context of the user-
defined data-types. For example:
complex c1(2.5, 5 ), c2, c3 ;
c3 = c1 + c2 ;
Cont.
• In the first statement, c1, c2 and c3 are declared as the
objects of a class named as complex.

• The second statement indicates that objects c1 and c2 are


added and assigned to the object c3.

• When the value of one object is assigned to another object


of the same type, the values of all the data members are
copied into the corresponding data members of the new
object.

• The compiler doesn’t need any special instruction to use =


for the assignment of the user-defined objects, such as
complex object.

• Thus, one can conclude that the assignments between data-


types (basic or user-defined) are handled by the compiler
without any need of special instructions, provided that same
data-type is used on both sides of the = sign.
Data Conversion between different data-types:
• Now take the case when variables on the two sides of the = are of
different types. In case of basic-type variables, the compiler handles the
conversion automatically. For example, consider the following
statements:

int i ;
float f = 7.5 ;
i=f;

• In the above first two statements, two variables i of integer type and f of
float type are declared.

• The variable f is initialized to a value 7.5.

• The third statement converts the variable f to an integer before its value
is assigned to i.

• Thus, the fractional part is truncated and the value 7 is assigned to i,


automatically.

• There are many other such conversions possible i.e. from float to double,
char to float and so on.
Cont.
• Each such conversion has its own routine built into the
compiler.

• These routines are called when the operands on either side of


the assignment operator are different.

• These conversions are known as implicit conversions since


these conversions are not apparent in the listing of the
program.

• There may be situation when one wants to force the compiler


to convert one type of data to another.

• This can be achieved using typecasting. The following example


illustrates this:

float a = 7.5 ;
int b ;
b = int( a ) ;
Cont.

• Typecasting provides an explicit conversion i.e., in the


listing it can be obviously seen that the int( ) conversion
function will convert a form float to an int. However,
such explicit conversions use the same built-in routines
as implicit conversions.
• When one wants to convert between user-defined data-
types and basic-types, one can’t rely on built-in
conversion routines since the compiler doesn’t know
anything about user-defined types. Thus, the users must
write the conversion routines by themselves, if such
operations are required.
There are three types of situations that may arise in
the data conversion between incompatible types.

• Conversion from built-in type to class type.

• Conversion from class type to built-in type.

• Conversion from one class type to another


class type.
Program: This program illustrates the conversion from built-in type to user
defined and from user-defined type to the built-in type
#include<iostream.h>
const float M = 1.61 ;
class Distconv
{
int Kmeter ;
float meter ;
public:
Distconv( ) // Default constructor without any argument
{ }
// This function converts built-in type i.e. mile to the user-defined type i.e. Distconv
Distconv(float mile) // Constructor with one argument
{
float Km = M * mile ; // converts mile to Km
Kmeter = int(Km); // converts float Km to int and assigns to
Kmeter
meter = (Km - Kmeter) * 1000 ; // converts to meter
}
Distconv(int k, float m) // Constructor with two arguments
{
Kmeter = k ;
meter = m ;
}
Cont.
void Display(void)
{
cout << Kmeter << " Kilometers and " << meter << " meters " ;
}

// ********Conversion Function************
operator float( ) // converts user-defined type i.e. Distconv to the
{ // basic-type i.e. meter
float K = meter/1000 ; // Converts the meters to Kilometers
K += float(Kmeter) ; // Adds the Kmeter
return K / M ; // Converts to mile
}
}; // End of the Class Definition
Cont.
void main(void)
{
Distconv d1 = 5.0 ; // Uses the constructor with one argument
cout << "\n d1 = " ;
d1.Display( ) ;

d1 = 2.0 ; // This form also uses the constructor with one argument
cout << "\n d1 = " ;
d1.Display( ) ;

Distconv d2( 2, 25.5 ); // Uses the constructor with two arguments


float ml = float(d2) ; // This form uses the conversion function and
// converts Distconv to mile
cout << "\n d2 = " << ml << " miles " ;
ml = d1 ; // This form also uses conversion function and
// converts Distconv to mile

cout << "\n d1 = " << ml << " miles " ;


}
Output:
Conversion from basic type to the user-defined (class) type:
• One can easily convert the basic-type to class-type, using a constructor. For
example, in the above program, a constructor with one argument is used,
which converts the basic type float to the user-defined type Distconv.

• The definition of this constructor is given as:

Distconv(float mile)
{
float Km = M * mile ;
Kmeter += int(Km) ;
meter = (Km – Kmeter) * 1000 ;
}

• This constructor is called when an object of type Distconv is created with a


single argument.

• In the above program, this is done by using the statement:

• Distconv d1 = 5.0 ;

• The function assumes that this argument represents mile. It converts the
argument to Km and meter.
Cont.
• Thus the conversion from mile to Distconv is carried out
along with the creation of an object in the statement:

Distconv d1 = 5.0 ;

• There is an another way to perform the same conversion. In


the main( ) program, after defining object d1 and displaying
its value, the following statement has been defined:

• d1 = 2.0 ;

• This statement also converts basic-type float to Distconv,


without creating a new object, by calling the one argument
constructor. But actually, this statement creates a nameless
temporary object with Kmeter and meter values
corresponding to 2.0 miles.
Conversion from user-Defined (class) type to basic type:
• The constructors do the job in type conversion from a basic type to the user-
defined type. But the constructors cannot be used when the conversion from the
user-defined type to the basic type is needed. However, C++ allows one to
define an overloaded casting operator that could be used to convert a class type
data to a basic type. This function is known as conversion function and its
general form is:

operator typeneme( )
{
statement(s) ;
}

• This function converts a user-defined data to the typename. For example, in the
program, the conversion function operator float ( ) converts a class object to
the type float. The definition of this function is given as:

Distconv :: operator float( )


{
float K = meter/1000 ;
K += float(K) ;
return (K/M) ;
}
Conversion between objects of different classes:
• The conversion between the objects of different classes can
also be done using one-argument constructor, or a
conversion function. The choice depends upon whether
the conversion routine has to be declared in the source
class or in the destination class. Now, what are the source
and the destination classes? To illustrate them consider a
program that contains two classes A and B. Also consider
that the main( ) function contains a statement:

object_A = object_B ;

• where object_A is an object of the class A and object_B is


an object of the class B. In above statement, the object_B
of type B is converted into the object_A of type A.
Therefore, object_B is an object of the source class B and
object_A is an object of the destination class A. The user
can use either the conversion function or the constructor
with one argument, depending on whether it has to be
specified in the source class or in the destination class.
Cont.

• Using Conversion Function


• Using Constructor with one argument
• If the user wants to use the conversion routine in
the source class B, then the conversion
function is used. If user wants to use the
conversion routine in the destination class A,
then the constructor with one argument is
used. Remember that the constructor in the
destination class A must be able to access the
data in the source class B to perform the
conversion.
Program using the conversion function:
// This program illustrates the conversion from one class to another class, using the conversion function.
#include<iostream.h>
class Distance1 // Destination class
{
private:
float Kmeter ;
public:
Distance1( )
{ Kmeter = 0.0 ; }
Distance1(float k)
{ Kmeter = k ; }
void display( )
{ cout << Kmeter << " Kilometers" ; }
};
class Distance2 // Source class
{
private:
int meter, cmeter;
public:
Distance2( )
{ meter = cmeter = 0 ; }
Distance2(int m, int c)
{
meter = m ;
cmeter = c ;
}
void display(void)
{ cout << meter << " Meters " << cmeter << " Centimeters" ; }
Cont.
operator Distance1 ( ) // Conversion Function
{
float Km = meter/1000.0 ;
Km += cmeter/100000.0 ;
return Distance1(Km) ;
}
}; // End of the class definition

void main(void)
{
Distance1 d1 ; // Object of the destination class
Distance2 d2(1000, 100) ; // Object of the source class
d1 = d2 ; // Conversion of type Distance2 to the type
Distance1
cout << "\n Distance2 = " ;
d2.display ( ) ;
cout << "\n Distance1 = " ;
d1.display( ) ;
}
Output:
Explanation
The above program, contains two classes: Distance1 and Distance2. In the
main( ) function the first statement is given as:

Distance d1 ;

which declares an object d1 of class Distance1.

The second statement is given as:

Distance d2(1000, 100) ;

which declares an object d2 of class Distance2 and initializes it to (1000, 100).

The third statement i.e.

d1 = d2 ;

converts the object d2 of the source class Distance2 to the object d1 of the destination class
Distance1.

The conversion function is declared in the source class Distance2 as:


operator Distance1 ( ) // Conversion Function
{
float Km = meter/1000.0 ;
Km += cmeter/100000.0 ;
return Distance1(Km) ;
}
Cont.
• This function transforms the object of
which it is a member to a Distance1
object, and returns this object, which
main( ) then assigns to Distance2.
This program illustrates the conversion from an object of a
class to the object of another class, using the constructor.
#include<iostream.h>
class Distance2 // Source class
{
private:
int meter, cmeter ;
public:
Distance2( )
{ meter = cmeter = 0 ; }
Distance2(int m, int c)
{ meter = m; cmeter = c;
}
void display(void)
{
cout << meter << "Meters " << cmeter << "Centimeters" ;
}
int getm(void) // This function allows the data member “meter” to be
{ // accessed from outside the class.
return meter ;
}
int getcm(void) // This function allows the data member “cmeter” to be
{ // accessed from outside the class.
return cmeter ;
}
} ;
Cont.
class Distance1 // Destination Class
{
private:
float Kmeter ;
public:
Distance1( )
{ Kmeter = 0.0; }
Distance1(float k)
{ Kmeter = k ; }

// Converstion routine
Distance1(Distance2 d2) // Constructor with an argument of type Distance2
{
float a = d2.getm( ); // Access “meter” from the class Distance2, using the
//member function getm( )
float b = d2.getcm( ); // Access “cmete”r from the class Distance2, using the
// member function getcm()
Kmeter = a/1000.0 + b/100000.0 ;
}
void display(void)
{ cout << Kmeter << " Kilometers" ; }
};
Cont.

void main(void)
{
Distance1 d1 ;
Distance2 d2(1000, 100);
d1 = d2 ;
cout << "\n Distance2 = " ; d2.display( );
cout << "\n Distance1 = " ; d1.display( );
}
Output:
Explanation
• Above program, uses the constructor with one
argument, to convert an object d2 of class Distance2 to
the object d1 of the class Distance1. Thus, the
conversion constructor is being used in the destination
class Distance1. To perform the conversion, this
constructor must be able to access the data members
(meter and cmeter) of the Distance1 object sent as an
argument. For this, the Distance1 class contains the
following member functions, defined in the public area:

int getm(void)
{ return meter ; }
int getcm(void)
{ return cmeter ; }
Cont.
• The one argument constructor is specified in the destination
class Distance1 as:

Distance1(Distance2 d2) // Constructor with an


// argument of type
Distance2
{
float a = d2.getm( );
float b = d2.getcm( );
Kmeter = a/1000.0 + b/100000.0 ;
}

This constructor converts the object (meter and cmeter) of the


class Distance2, to the object (kmeter) of Distance1 class
type.

You might also like