SlideShare a Scribd company logo
Chapter 4
Operator Overloading
Outline:
4.1. Introduction to ooperator overloading
4.2. The ‘this’ operator
4.3. Syntax of operator overloading
4.4.Restriction on operator overloading
4.5. Implementation of operator overloading
4.6 Data Conversion
1
4.1. Introduction to operator overloading
 Operator overloading enables us to extend(give additional
meaning) most of the built-in C++ operators.
 The meaning of a given overloaded operator varies on use.
 Consider the standard + (plus) operator. When this operator is used
with operands of different standard types, the operator has slightly
different meanings. For example, the addition of two integers is not
implemented in the same way as the addition of two floating-point
numbers.
 C++ allows you to define your own meanings for the standard C++
operators when they are applied to class types.
2
4.1. Introduction to operator overloading
(Continued… )
 The process of operator overloading involves the
following steps:
1. Create a class that defines the data type that is to be used in
the overloading operation.
2. Declare the operator function operator op() in the public
part of the class. It may be either a member function or a
friend function.
3.Define the operator function to implement the required
operation.
3
‘this’ pointer
 The ‘this’ pointer points to the object for which the member function is called. It is non-
modifiable pointer that stores the address of a class instance and it is not counted in the
calculation of the size of the object. Static member functions do not have a this pointer. When a
non-static member function is called for an object, the address of the object is passed by the
compiler as a hidden argument to the function.
 For example, the following function call: myDate.setMonth( 3 ); Can be interpreted this way:
setMonth( &myDate, 3 );
 The object's address is available from within the member function as the this pointer. Most uses of
this are implicit. It is legal, though unnecessary, to explicitly use this when referring to members
of the class. For example:
void Date::setMonth( int mn )
{ // These following three statements are equivalent
month = mn; this->month = mn; (*this).month = mn;
}
 The expression *this is commonly used to return the current object from a member function:
return *this;
4
Syntax of Operator Overloading
 Overloaded operators are implemented as functions and can be member functions of a
given class or global functions. Like any other function, an overloaded operator has a
return type and a parameter list.
 Syntax: return-type class name:: operator@(argument-list) {…}
 Most of C++ built-in operators are overloadable except the scope resolution
operator(::), class member access operator(.),ternary operator(?:) and the
sizeof operator.
 The next slide shows the list of the overloadable C++ operators.
---operator is a function
--- @ is one of built-in overloadable C++ operator symbols (+, -, =, etc..)
--- For example : operator+() would be used to overload the addition operator (+)
5
Overloadable C++ Operators
6
Operatorsthatcanbeoverloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]
Restrictions on operator overloading
 Although the semantics of an operator can be extended , you can’t change its
syntax.
 Note the following restriction on overloading :
 The order of precedence cannot be changed for overloaded operators
 Default arguments may not be used with overloaded operators
 New operators cannot be created
 Overloading must be explicit, i.e. overloading + does not imply += is
overloaded
 The arity (number of operands) cannot be changed. Unary operators remain
unary, and binary operators remain binary
 Operators &, *, + and - each have unary and binary versions
• Unary and binary versions can be overloaded separately
7
Implementing Operator Overloading
 There are 2 ways to implement operator overloading :
1. Implemented as member functions
• Expression obj1@ or @obj2 translates into a function call obj1.operator@() or
obj2.operator@() [For Unary operators]
• Expression obj1@obj2 translates into a function call obj1.operator@(obj2)
[For Binary operators]
2.Implemented as non-member or Friend functions
• Expression obj1@ or @obj2 translates into a function call operator@(obj1) or
operator@(obj2) [For Unary operators]
• Expression obj1@obj2 translates into a function call operator@(obj1,obj2)
[For Binary operators]
• The operator function may need to be declared as a friend if it requires
access to protected or private data
8
9
class Complex {
...
public:
...
Complex operator +(const Complex &op)
{
double real = real + op.real,
imag = imag + op. imag;
return(Complex(real, imag));
}
...
};
c = a+b;
c = a.operator+ (b);
Implementing Operator Overloading :
1. Defined as a member function
10
c = a+b;
c = operator+ (a,b);
Implementing Operator Overloading :
2. Defined as a non-member function
Complex operator +(Complex &op1, Complex &op2)
{
double real = op1.real() + op2.real();
double imag = op1.imag() + op2.imag();
return(Complex(real, imag));
}
class Complex {
...
public:
...
double real() { return real; }
//need access functions
double imag() { return imag; }
...
};
11
class Complex {
...
public:
...
friend Complex operator +( const Complex &, const
Complex & );
...
};
Complex operator +(Complex &op1, Complex &op2)
{
double real = op1.real + op2.real,
imag = op1.imag + op2.imag;
return(Complex(real, imag));
}
c = a+b;
c = operator+ (a, b);
Implementing Operator Overloading :
3. Defined as a friend function
Overloading unary operators
 The unary operators operate on a single operand and the following are
examples of unary operators:
• The unary minus (-) operator.
• The logical not (!) operator.
• The increment (++) and decrement (--) operators
 The unary operators operate on the object for which they were called and
normally, this operator appears on the left side of the object, as in !obj, -obj, and
++obj but sometime they can be used as postfix as well like obj++ or obj--.
 Observe the example shown in the next slide(s):
12
Overloading unary operators: Example
class Distance
{ private:
int feet, inches;
public:
Distance(){ feet = 0; inches = 0; }
Distance(int f, int i){feet = f; inches = i; }
void displayDistance()
{ cout << "F: " << feet << " I:" << inches <<endl; }
// overloaded minus (-) operator
Distance operator- ()
{ feet = -feet; inches = -inches;
return Distance(feet, inches);
}
};
13
Overloading unary operators: Example 1
(continued…)
int main()
{
Distance D1(11, 10), D2(-5, 11);
-D1; // apply negation
D1.displayDistance(); // display D1
-D2; // apply negation
D2.displayDistance(); // display D2
return 0;
}
When the above code is compiled and executed, it produces following result:
F: -11 I:-10
F: 5 I:-11
14
Overloading binary operators: Example
#include <iostream>
using namespace std;
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setValues( double l, double b, double h )
{
length = l;
breadth = b;
height = h;
}
15
Overloading binary operators:
Example(continued…)
Box operator+(const Box& b) // Overload + operator to add two Box objects.
{ Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
16
Overloading binary operators:
Example(continued…)
int main( )
{ Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
Box1.setValues(6.0,7.0,5.0);
Box2.setValues(12.0,13.0,10.0);
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
Box3 = Box1 + Box2;
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
17
Overloading relational operators: Example
class Distance
{ private:
int feet; int inches;
public:
Distance(){ feet = 0; inches = 0; }
Distance(int f, int i){feet = f; inches = i; }
void displayDistance()
{ cout << "F: " << feet << " I:" << inches <<endl; }
// overloaded less than (<) operator
bool operator < (const Distance &d)
{ if(feet <d.feet)
{ return true;}
if(feet == d.feet && inches < d.inches) { return true;}
return false;
}
};
18
Overloading relational operators: Example
(continued…)
int main()
{
Distance D1(11, 10), D2(-5, 11);
if(D1<D2)
{
cout<<“D1 is less than D2”<<endl;
}
else
{
cout<<“D2 is less than D1”<<endl;
}
return 0;
}
When the above code is compiled and executed, it produces following result:
D2 is less than D1
19
4.2 Data Conversion
 When constants and variables of different types are mixed in an expression,
automatic type conversion will be applied to the operands based on certain rules.
 A simple rule is that the type of data to the right of an assignment operator is
automatically converted to the type of the variable on the left.
 For example, the statements :
int m;
float x=3.14159;
m=x;
 What will be the value of m?
 x will be converted to an integer before its value is assigned to m.
 What happens when we deal with user-defined data types
20
4.2 Data Conversion(Continued…)
 Consider the following statement that adds two objects and then assigns the result to a
third object:
• Obj3 = Obj1 + Obj2 ;
 If the objects are of the same class type, the operations of addition and assignment are
carried out smoothly and the compiler doesn’t make any complaints.
 What if one of the operands is an object and the other is a built-in type variable? Or, what
if they belong to two different classes?
 The compiler doesn’t support automatic type conversions for such data types. Therefore,
we must design the conversion routines by ourselves , if such operations are required.
 Three types of situations might arise in the data conversion between incompatible types :
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
21
4.2 Data Conversion(Continued…)
1.Conversion from basic type to class type
This type of conversion is easy to accomplish. The constructors of a given class are responsible for
the convert process.
Example:
class time
{ int hours;
int minutes;
public:
…
time(int t)
{
hours=t/60;
minutes=t%60;
}
};
22
4.2 Data Conversion(Continued…)
1.Conversion from basic type to class type(continued…)
The following conversion statements can be used in a function:
time T1;
int duration = 85;
//int to class type conversion. Note the left-hand operand of = operator is always a class object
T1 = duration;
After this conversion, the hours data member of the object T1 will contain a value of 1 and the
minutes data member a value of 25, denoting 1 hour and 25 minutes.
23
4.2 Data Conversion(Continued…)
2.Conversion from class type to basic type
 The constructor function doesn’t support this operation.
 C++ allows us to define an overloaded casting operator that could be used to convert a class type
data to a basic type.
 The general format of an overloaded casting operator function, usually referred to as a conversion
function , is :
 Operator typename()
 {
…
… (Function statements)
…
}
24
4.2 Data Conversion(Continued…)
2.Conversion from class type to basic type(continued…)
 Consider the following conversion function:
vector :: Operator double()
{ double sum=0;
for(int i=0;i<size;i++)
sum=sum+v[i]*u[i];
return sqrt(sum);
}
Now the operator double() can be used as follows:
double length = double(v1); Or double length = v1;
Where v1 is an object of type class vector.
The casting operator function should satisfy the following conditions:
1. It must be a class member
2. It must not specify a return type
3. It must not have any arguments
25
4.2 Data Conversion(Continued…)
3. One class type to another class type
 There might be some situations where we would like to convert one class type data to another class
type. Such conversion can be carried out by either a constructor or a conversion function.
 Example: ObjX = ObjY; // Objects of different classes
 In this example, the class Y data is converted to the class X type data and the converted value is
assigned to the ObjX.
 Class Y is called the source class and class X is known as the destination class.
26
Reading Assignment
 Read more about data conversion from one class type to another
class type and come up with appropriate example and show that
your example works properly during the lab hours.
End of slides
 If you have any question?

More Related Content

PPTX
3. Polymorphism.pptx
PDF
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
PPTX
Operator overloaing
PDF
Polymorphism and Type Conversion.pdf pot
PDF
NIKUL SURANI
PDF
Operator overloading
PPTX
Operator Overloading
PPTX
Operator overloading
3. Polymorphism.pptx
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
Operator overloaing
Polymorphism and Type Conversion.pdf pot
NIKUL SURANI
Operator overloading
Operator Overloading
Operator overloading

Similar to Ch-4-Operator Overloading.pdf (20)

PPTX
B.sc CSIT 2nd semester C++ Unit4
PDF
Object Oriented Programming using C++ - Part 3
PDF
Unit3_OOP-converted.pdf
PDF
22 scheme OOPs with C++ BCS306B_module3.pdf
PPTX
PPT
Lec 26.27-operator overloading
PPT
Overloading
PPTX
Operator overloading
PDF
Lec 8.pdf a
PPTX
Operator overloading2
PPTX
operator overloading
PPTX
operator overloading
PPT
Operator Overloading
PPTX
Operator overloading
PDF
Operator_Overloaing_Type_Conversion_OOPC(C++)
PPT
Lec 28 - operator overloading
PPT
Lecture5
PPTX
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
PPT
14 operator overloading
PPT
OperatorOverloading.ppt
B.sc CSIT 2nd semester C++ Unit4
Object Oriented Programming using C++ - Part 3
Unit3_OOP-converted.pdf
22 scheme OOPs with C++ BCS306B_module3.pdf
Lec 26.27-operator overloading
Overloading
Operator overloading
Lec 8.pdf a
Operator overloading2
operator overloading
operator overloading
Operator Overloading
Operator overloading
Operator_Overloaing_Type_Conversion_OOPC(C++)
Lec 28 - operator overloading
Lecture5
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
14 operator overloading
OperatorOverloading.ppt
Ad

Recently uploaded (20)

PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
history of c programming in notes for students .pptx
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
System and Network Administration Chapter 2
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
top salesforce developer skills in 2025.pdf
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
medical staffing services at VALiNTRY
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
Essential Infomation Tech presentation.pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Odoo Companies in India – Driving Business Transformation.pdf
Design an Analysis of Algorithms II-SECS-1021-03
wealthsignaloriginal-com-DS-text-... (1).pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
history of c programming in notes for students .pptx
PTS Company Brochure 2025 (1).pdf.......
System and Network Administration Chapter 2
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
top salesforce developer skills in 2025.pdf
Operating system designcfffgfgggggggvggggggggg
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Which alternative to Crystal Reports is best for small or large businesses.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
medical staffing services at VALiNTRY
How to Choose the Right IT Partner for Your Business in Malaysia
Reimagine Home Health with the Power of Agentic AI​
Essential Infomation Tech presentation.pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Odoo Companies in India – Driving Business Transformation.pdf
Ad

Ch-4-Operator Overloading.pdf

  • 1. Chapter 4 Operator Overloading Outline: 4.1. Introduction to ooperator overloading 4.2. The ‘this’ operator 4.3. Syntax of operator overloading 4.4.Restriction on operator overloading 4.5. Implementation of operator overloading 4.6 Data Conversion 1
  • 2. 4.1. Introduction to operator overloading  Operator overloading enables us to extend(give additional meaning) most of the built-in C++ operators.  The meaning of a given overloaded operator varies on use.  Consider the standard + (plus) operator. When this operator is used with operands of different standard types, the operator has slightly different meanings. For example, the addition of two integers is not implemented in the same way as the addition of two floating-point numbers.  C++ allows you to define your own meanings for the standard C++ operators when they are applied to class types. 2
  • 3. 4.1. Introduction to operator overloading (Continued… )  The process of operator overloading involves the following steps: 1. Create a class that defines the data type that is to be used in the overloading operation. 2. Declare the operator function operator op() in the public part of the class. It may be either a member function or a friend function. 3.Define the operator function to implement the required operation. 3
  • 4. ‘this’ pointer  The ‘this’ pointer points to the object for which the member function is called. It is non- modifiable pointer that stores the address of a class instance and it is not counted in the calculation of the size of the object. Static member functions do not have a this pointer. When a non-static member function is called for an object, the address of the object is passed by the compiler as a hidden argument to the function.  For example, the following function call: myDate.setMonth( 3 ); Can be interpreted this way: setMonth( &myDate, 3 );  The object's address is available from within the member function as the this pointer. Most uses of this are implicit. It is legal, though unnecessary, to explicitly use this when referring to members of the class. For example: void Date::setMonth( int mn ) { // These following three statements are equivalent month = mn; this->month = mn; (*this).month = mn; }  The expression *this is commonly used to return the current object from a member function: return *this; 4
  • 5. Syntax of Operator Overloading  Overloaded operators are implemented as functions and can be member functions of a given class or global functions. Like any other function, an overloaded operator has a return type and a parameter list.  Syntax: return-type class name:: operator@(argument-list) {…}  Most of C++ built-in operators are overloadable except the scope resolution operator(::), class member access operator(.),ternary operator(?:) and the sizeof operator.  The next slide shows the list of the overloadable C++ operators. ---operator is a function --- @ is one of built-in overloadable C++ operator symbols (+, -, =, etc..) --- For example : operator+() would be used to overload the addition operator (+) 5
  • 6. Overloadable C++ Operators 6 Operatorsthatcanbeoverloaded + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete new[] delete[]
  • 7. Restrictions on operator overloading  Although the semantics of an operator can be extended , you can’t change its syntax.  Note the following restriction on overloading :  The order of precedence cannot be changed for overloaded operators  Default arguments may not be used with overloaded operators  New operators cannot be created  Overloading must be explicit, i.e. overloading + does not imply += is overloaded  The arity (number of operands) cannot be changed. Unary operators remain unary, and binary operators remain binary  Operators &, *, + and - each have unary and binary versions • Unary and binary versions can be overloaded separately 7
  • 8. Implementing Operator Overloading  There are 2 ways to implement operator overloading : 1. Implemented as member functions • Expression obj1@ or @obj2 translates into a function call obj1.operator@() or obj2.operator@() [For Unary operators] • Expression obj1@obj2 translates into a function call obj1.operator@(obj2) [For Binary operators] 2.Implemented as non-member or Friend functions • Expression obj1@ or @obj2 translates into a function call operator@(obj1) or operator@(obj2) [For Unary operators] • Expression obj1@obj2 translates into a function call operator@(obj1,obj2) [For Binary operators] • The operator function may need to be declared as a friend if it requires access to protected or private data 8
  • 9. 9 class Complex { ... public: ... Complex operator +(const Complex &op) { double real = real + op.real, imag = imag + op. imag; return(Complex(real, imag)); } ... }; c = a+b; c = a.operator+ (b); Implementing Operator Overloading : 1. Defined as a member function
  • 10. 10 c = a+b; c = operator+ (a,b); Implementing Operator Overloading : 2. Defined as a non-member function Complex operator +(Complex &op1, Complex &op2) { double real = op1.real() + op2.real(); double imag = op1.imag() + op2.imag(); return(Complex(real, imag)); } class Complex { ... public: ... double real() { return real; } //need access functions double imag() { return imag; } ... };
  • 11. 11 class Complex { ... public: ... friend Complex operator +( const Complex &, const Complex & ); ... }; Complex operator +(Complex &op1, Complex &op2) { double real = op1.real + op2.real, imag = op1.imag + op2.imag; return(Complex(real, imag)); } c = a+b; c = operator+ (a, b); Implementing Operator Overloading : 3. Defined as a friend function
  • 12. Overloading unary operators  The unary operators operate on a single operand and the following are examples of unary operators: • The unary minus (-) operator. • The logical not (!) operator. • The increment (++) and decrement (--) operators  The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj--.  Observe the example shown in the next slide(s): 12
  • 13. Overloading unary operators: Example class Distance { private: int feet, inches; public: Distance(){ feet = 0; inches = 0; } Distance(int f, int i){feet = f; inches = i; } void displayDistance() { cout << "F: " << feet << " I:" << inches <<endl; } // overloaded minus (-) operator Distance operator- () { feet = -feet; inches = -inches; return Distance(feet, inches); } }; 13
  • 14. Overloading unary operators: Example 1 (continued…) int main() { Distance D1(11, 10), D2(-5, 11); -D1; // apply negation D1.displayDistance(); // display D1 -D2; // apply negation D2.displayDistance(); // display D2 return 0; } When the above code is compiled and executed, it produces following result: F: -11 I:-10 F: 5 I:-11 14
  • 15. Overloading binary operators: Example #include <iostream> using namespace std; class Box { public: double getVolume(void) { return length * breadth * height; } void setValues( double l, double b, double h ) { length = l; breadth = b; height = h; } 15
  • 16. Overloading binary operators: Example(continued…) Box operator+(const Box& b) // Overload + operator to add two Box objects. { Box box; box.length = this->length + b.length; box.breadth = this->breadth + b.breadth; box.height = this->height + b.height; return box; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; 16
  • 17. Overloading binary operators: Example(continued…) int main( ) { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Box Box3; // Declare Box3 of type Box double volume = 0.0; // Store the volume of a box here Box1.setValues(6.0,7.0,5.0); Box2.setValues(12.0,13.0,10.0); volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; Box3 = Box1 + Box2; volume = Box3.getVolume(); cout << "Volume of Box3 : " << volume <<endl; return 0; } 17
  • 18. Overloading relational operators: Example class Distance { private: int feet; int inches; public: Distance(){ feet = 0; inches = 0; } Distance(int f, int i){feet = f; inches = i; } void displayDistance() { cout << "F: " << feet << " I:" << inches <<endl; } // overloaded less than (<) operator bool operator < (const Distance &d) { if(feet <d.feet) { return true;} if(feet == d.feet && inches < d.inches) { return true;} return false; } }; 18
  • 19. Overloading relational operators: Example (continued…) int main() { Distance D1(11, 10), D2(-5, 11); if(D1<D2) { cout<<“D1 is less than D2”<<endl; } else { cout<<“D2 is less than D1”<<endl; } return 0; } When the above code is compiled and executed, it produces following result: D2 is less than D1 19
  • 20. 4.2 Data Conversion  When constants and variables of different types are mixed in an expression, automatic type conversion will be applied to the operands based on certain rules.  A simple rule is that the type of data to the right of an assignment operator is automatically converted to the type of the variable on the left.  For example, the statements : int m; float x=3.14159; m=x;  What will be the value of m?  x will be converted to an integer before its value is assigned to m.  What happens when we deal with user-defined data types 20
  • 21. 4.2 Data Conversion(Continued…)  Consider the following statement that adds two objects and then assigns the result to a third object: • Obj3 = Obj1 + Obj2 ;  If the objects are of the same class type, the operations of addition and assignment are carried out smoothly and the compiler doesn’t make any complaints.  What if one of the operands is an object and the other is a built-in type variable? Or, what if they belong to two different classes?  The compiler doesn’t support automatic type conversions for such data types. Therefore, we must design the conversion routines by ourselves , if such operations are required.  Three types of situations might arise in the data conversion between incompatible types : 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 21
  • 22. 4.2 Data Conversion(Continued…) 1.Conversion from basic type to class type This type of conversion is easy to accomplish. The constructors of a given class are responsible for the convert process. Example: class time { int hours; int minutes; public: … time(int t) { hours=t/60; minutes=t%60; } }; 22
  • 23. 4.2 Data Conversion(Continued…) 1.Conversion from basic type to class type(continued…) The following conversion statements can be used in a function: time T1; int duration = 85; //int to class type conversion. Note the left-hand operand of = operator is always a class object T1 = duration; After this conversion, the hours data member of the object T1 will contain a value of 1 and the minutes data member a value of 25, denoting 1 hour and 25 minutes. 23
  • 24. 4.2 Data Conversion(Continued…) 2.Conversion from class type to basic type  The constructor function doesn’t support this operation.  C++ allows us to define an overloaded casting operator that could be used to convert a class type data to a basic type.  The general format of an overloaded casting operator function, usually referred to as a conversion function , is :  Operator typename()  { … … (Function statements) … } 24
  • 25. 4.2 Data Conversion(Continued…) 2.Conversion from class type to basic type(continued…)  Consider the following conversion function: vector :: Operator double() { double sum=0; for(int i=0;i<size;i++) sum=sum+v[i]*u[i]; return sqrt(sum); } Now the operator double() can be used as follows: double length = double(v1); Or double length = v1; Where v1 is an object of type class vector. The casting operator function should satisfy the following conditions: 1. It must be a class member 2. It must not specify a return type 3. It must not have any arguments 25
  • 26. 4.2 Data Conversion(Continued…) 3. One class type to another class type  There might be some situations where we would like to convert one class type data to another class type. Such conversion can be carried out by either a constructor or a conversion function.  Example: ObjX = ObjY; // Objects of different classes  In this example, the class Y data is converted to the class X type data and the converted value is assigned to the ObjX.  Class Y is called the source class and class X is known as the destination class. 26
  • 27. Reading Assignment  Read more about data conversion from one class type to another class type and come up with appropriate example and show that your example works properly during the lab hours.
  • 28. End of slides  If you have any question?