SlideShare une entreprise Scribd logo
1  sur  42
Télécharger pour lire hors ligne
Chap 7
Operator Overloading & Type
Conversion
1 By:-Gourav Kottawar
Contents
7.1 Defining operator Overloading
7.2 Overloading Unary Operator
7.3 Overloading Binary Operator
7.4 Overloading Binary Operator Using
Friend function
7.5 Manipulating of String Using
Operators
7.6 Type Conversion
7.7 Rules for Overloading Operators
2 By:-Gourav Kottawar
Introduction
 Important technique allows C++ user
defined data types behave in much the
same way as built in types.
 C++ has ability to provide the operators
with a special meanings for a data type.
 The mechanism of giving such special
meaning to an operator is known as
operator overloading.
3 By:-Gourav Kottawar
By:-Gourav Kottawar4
Why Operator Overloading?
 Readable code
 Extension of language to include user-defined
types
 I.e., classes
 Make operators sensitive to context
 Generalization of function overloading
By:-Gourav Kottawar5
Simple Example
class complex {
double real, imag;
public:
complex(double r, double i) :
real(r), imag(i) {}
}
 Would like to be able to write:–
complex a = complex(1, 3.0);
complex b = complex(1.2, 2);
complex c = b;
a = b + c;
b = b+c*a;
c = a*b + complex(1,2);
I.e., would like to write
ordinary arithmetic expressions
on this user-defined class.
By:-Gourav Kottawar6
With Operator Overloading, We
Can
class complex {
double real, imag;
public:
complex(double r, double i) :
real(r), imag(i) {}
complex operator+(complex a, complex b);
complex operator*(complex a, complex b);
complex& operator=(complex a, complex b);
...
}
By:-Gourav Kottawar7
General Format
returnType operator*(parameters);
  
any type keyword operator symbol
 Return type may be whatever the operator
returns
 Including a reference to the object of the operand
 Operator symbol may be any overloadable
operator from the list.
By:-Gourav Kottawar8
C++ Philosophy
 All operators have context
 Even the simple “built-in” operators of basic types
 E.g., '+', '-', '*', '/' for numerical types
 Compiler generators different code depending upon type of
operands
 Operator overloading is a generalization of this
feature to non-built-in types
 E.g., '<<', '>>' for bit-shift operations and also for
stream operations
By:-Gourav Kottawar9
C++ Philosophy (continued)
 Operators retain their precedence and
associativity, even when overloaded
 Operators retain their number of operands
 Cannot redefine operators on built-in types
 Not possible to define new operators
 Only (a subset of) the built-in C++ operators can be
overloaded
Restrictions on Operator Overloading
 C++ operators that can be overloaded
 C++ Operators that cannot be overloaded
Operators that cannot be overloaded
. .* :: ?: sizeof
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]
10 By:-Gourav Kottawar
7.2 Overloading Unary Operator
11 By:-Gourav Kottawar
#include <iostream>
using namespace std;
class temp
{
private:
int count;
public:
temp():count(5)
{ }
void operator ++()
{
count=count+1;
}
void Display()
{
cout<<"Count:
"<<count;
}
};
int main()
{
temp t;
++t;
/* operator function void
operator ++() is called */
t.Display();
return 0;
}
12 By:-Gourav Kottawar
#include <iostream>
using namespace std;
class temp
{
private:
int count;
public:
temp():count(5)
{ }
void operator ++()
{
count=count+1;
}
void Display()
{
cout<<"Count:
"<<count;
}
};
int main()
{
temp t;
++t;
/* operator function void
operator ++() is called */
t.Display();
return 0;
}
Output
Count: 6
13 By:-Gourav Kottawar
Note
 Operator overloading cannot be used to change the
way operator works on built-in types. Operator
overloading only allows to redefine the meaning of
operator for user-defined types.
 There are two operators assignment operator(=) and
address operator(&) which does not need to be
overloaded. Because these two operators are already
overloaded in C++ library. For example: If obj1 and
obj2 are two objects of same class then, you can use
code obj1=obj2; without overloading = operator. This
code will copy the contents object of obj2 to obj1.
Similarly, you can use address operator directly
without overloading which will return the address of
object in memory.
 Operator overloading cannot change the precedence
14 By:-Gourav Kottawar
7.3 Overloading Binary Operator
#include<iostream.h>
#include<conio.h>
class complex
{
int a,b;
public:
void getvalue()
{
cout<<"Enter the
value of Complex Numbers
a,b:";
cin>>a>>b;
}
complex
operator+(complex ob)
{ complex t;
t.a=ob.a +a;
t.b=ob.b+b;
return(t);
}
complex operator-(complex ob)
{
complex t;
t.a=ob.a - a;
t.b=ob.b -b;
return(t);
}
void display()
{
cout<<a<<"+"<<b<<"i"
<<"n";
}
};
15 By:-Gourav Kottawar
void main()
{
clrscr();
complex
obj1,obj2,result,result1;
obj1.getvalue();
obj2.getvalue();
result = obj1+obj2;
result1=obj1-obj2;
cout<<"Input Values:n";
obj1.display();
obj2.display();
cout<<"Result:";
result.display();
result1.display();
getch();
}
16 By:-Gourav Kottawar
void main()
{
clrscr();
complex
obj1,obj2,result,result1;
obj1.getvalue();
obj2.getvalue();
result = obj1+obj2;
result1=obj1-obj2;
cout<<"Input Values:n";
obj1.display();
obj2.display();
cout<<"Result:";
result.display();
result1.display();
getch();
}
In overloading of binary operators the left hand operand
is used to invoke the operator function and the right hand
operand is passed as an argument.17 By:-Gourav Kottawar
7.5 Overloading Binary operators using
Friend
 Friend function can be used to overload binary
operator.
 Required two arguments to be passed explicitly.#include <iostream>
using namespace std;
#include <conio.h>
class s
{
public:
int i,j;
s()
{ i=j=0;}
void disp(){cout << i <<" " <<
j;}
void getdata(){cin>>i>>j;}
friend s operator+(int,s);
};
s operator+(int a, s s1)
{ s k;
k.i = a+s1.i;
k.j = a+s1.j;
return k;
}
int main()
{ s s2;
s2.getdata();
s s3 = 10+s2;
s3.disp();
getch();
return 0;
}18 By:-Gourav Kottawar
#include<iostream.h>
class stud
{
int rno;
char *name;
int marks;
public:
friend istream &operator>>(istream
&,stud &);
friend void operator<<(ostream
&,stud &);
};
istream &operator>>(istream
&tin,stud &s)
{
cout<<"n Enter the no";
tin>>s.rno;
cout<<"n Enter the name";
tin>>s.name;
cout<<"n Enter Marks";
tin>>s.marks;
return tin;
void operator<<(ostream &tout,stud &s)
{
tout<<”n”<<s.rno;
tout<<”n”<<s.name;
tout<<”n”<<s.marks;
}
void main()
{
cout<<"ttBinaryOperator Overloading
Using FriendFunction";
stud s[3];
for(int i=0;i<3;i++)
{
cin>>s[i];
}
for( i=0;i<3;i++)
{
cout<<s[i];
}
getch();
}19 By:-Gourav Kottawar
Manipulation of Strings using Operators
 There are lot of limitations in string manipulation in C
as well as in C++.
 Implementation of strings require character arrays,
pointers and string functions.
 C++ permits us to create our own definitions of
operators that can be used to manipulate the strings
very much similar to other built-in data types.
 ANSI C++ committee has added a new class called
string to the C++ class library that supports all kinds of
string manipulations.20 By:-Gourav Kottawar
Manipulation of Strings using Operators
 Strings can be defined as class objects which can be
then manipulated like the built-in types.
 Since the strings vary in size, we use new to allocate
memory for each string and a pointer variable to point
to the string array.
continue…
21 By:-Gourav Kottawar
Manipulation of Strings using Operators
 We must create string objects that can hold two pieces
of information:
 Length
 Location
class string
{
char *p; // pointer to string
int len; // length of string
public :
------
------
};
continue…
22 By:-Gourav Kottawar
// string manipulation
#include<iostream.h>
#include<string.h>
class string
{
char str[25];
public:
void getstring();
void putstring(string&);
void display();
string operator+(string&);
int operator==(string&);
void operator=(string&);
void operator+=(string&);
};
void string::getstring()
{
cout<<"Enter string:";
gets(str);
}
void string::putstring(string &s)
{
int len=strlen(s.str);
cout<<len;
}
23 By:-Gourav Kottawar
string string::operator+(string
&s)
{
string temp;
if((strlen(str)+strlen(s.str))<25)
{
strcpy(temp.str,s.str);
strcat(temp.str,s.str);
}
else
{
cout<<endl<<"nconcatenation
is not possible";
}
return temp;
}
int string::operator==(string &s)
{
return(strcmp(str,s.str)==0?1:0)
;
}
void string::operator=(string
&s)
{
strcpy(str,s.str);
}
void string::operator+=(string
&s)
{
strcat(str,s.str);
}
void string::display()
{
cout<<str;
24 By:-Gourav Kottawar
void main()
{
string s1,s2,s3,s4;
clrscr();
s1.getstring();
s2.getstring();
s3=s1+s2;
cout<<"nFirst string length=";
s1.putstring(s1);
cout<<"nSecond string
length=";
s2.putstring(s2);
cout<<endl<<"nConcatenate
d string:";
s3.display();
if(s1==s2)
cout<<endl<<"nComparison:
Equal";
else
cout<<endl<<"nComparison:
Not equaln";
cout<<endl<<"nafter
addition:n";
s1+=s2;
s1.display();
s4=s3;
cout<<endl<<"copy:";
s4.display();
s1=s2;
getch();
25 By:-Gourav Kottawar
Rules For Overloading
Operators
 Only existing operators can be overloaded. New
operators cannot be created.
 The overloaded operator must have at least one
operand that is of user-defined type.
 We cannot change the basic meaning of an operator.
 Overloaded operators follow the syntax rules of the
original operators.
26 By:-Gourav Kottawar
Rules For Overloading
Operators
 The following operators that cannot be overloaded:
 Size of Size of operator
 . Membership operator
 .* Pointer-to-member operator
 : : Scope resolution operator
 ? ; Conditional operator
continue…
27 By:-Gourav Kottawar
Rules For Overloading
Operators
 The following operators can be over loaded with the
use of member functions and not by the use of friend
functions:
 Assignment operator =
 Function call operator( )
 Subscripting operator [ ]
 Class member access operator ->
 Unary operators, overloaded by means of a member
function, take no explicit arguments and return no
explicit values, but, those overloaded by means of a
friend function, take one reference argument.
continue…
28 By:-Gourav Kottawar
Rules For Overloading
Operators
 Binary operators overloaded through a member
function take one explicit argument and those which
are overloaded through a friend function take two
explicit arguments.
 When using binary operators overloaded through a
member function, the left hand operand must be an
object of the relevant class.
 Binary arithmetic operators such as +, -, * and / must
explicitly return a value. They must not attempt to
change their own arguments.
continue…
29 By:-Gourav Kottawar
Type Conversions
 The type conversions are automatic only when the
data types involved are built-in types.
int m;
float x = 3.14159;
m = x; // convert x to integer before its value is assigned
// to m.
 For user defined data types, the compiler does not
support automatic type conversions.
 We must design the conversion routines by
ourselves.
30 By:-Gourav Kottawar
Type Conversions
Different situations of data conversion between
incompatible types.
 Conversion from basic type to class type.
 Conversion from class type to basic type.
 Conversion from one class type to another
class type.
continue…
31 By:-Gourav Kottawar
Basic to Class Type
A constructor to build a string type object from a
char * type variable.
string : : string(char *a)
{
length = strlen(a);
P = new char[length+1];
strcpy(P,a);
}
The variables length and p are data members of
the class string.
32 By:-Gourav Kottawar
Basic to Class Type
string s1, s2;
string name1 = “IBM PC”;
string name2 = “Apple Computers”;
s1 = string(name1);
s2 = name2;
continue…
First converts name1 from char*
type to string type and then
assigns the string type value to
the object s1.
First converts name2 from char*
type to string type and then
assigns the string type value to
the object s2.
33 By:-Gourav Kottawar
Basic to Class Type
class time
{ int hrs ;
int mins ;
public :
…
time (int t)
{
hrs = t / 60 ;
mins = t % 60;
}
} ;
time T1;
int duration = 85;
T1 = duration;
continue…
34 By:-Gourav Kottawar
Class To Basic Type
A constructor function do not support type conversion
from a class type to a basic type.
An overloaded casting operator is used to convert a
class type data to a basic type.
It is also referred to as conversion function.
operator typename( )
{
…
… ( function statements )
…
}
This function converts a calss type data to typename.
35 By:-Gourav Kottawar
Class To Basic Type
vector : : operator double( )
{
double sum = 0;
for (int i=0; i < size ; i++)
sum = sum + v[i] * v[i];
return sqrt (sum);
}
This function converts a vector to the square root of the
sum of squares of its components.
continue…
36 By:-Gourav Kottawar
Class To Basic Type
The casting operator function should satisfy the following
conditions:
 It must be a class member.
 It must not specify a return type.
 It must not have any arguments.
vector : : operator double( )
{
double sum = 0;
for (int i=0; i < size ; i++)
sum = sum + v[i] * v[i];
return sqrt (sum);
}
continue…
37 By:-Gourav Kottawar
Class To Basic Type
 Conversion functions are member functions and
it is invoked with objects.
 Therefore the values used for conversion inside
the function belong to the object that invoked
the function.
 This means that the function does not need an
argument.
continue…
38 By:-Gourav Kottawar
One Class To Another Class
Type
objX = objY ; // objects of different types
 objX is an object of class X and objY is an object of
class Y.
 The class Y type data is converted to the class X type
data and the converted value is assigned to the objX.
 Conversion is takes place from class Y to class X.
 Y is known as source class.
 X is known as destination class.
39 By:-Gourav Kottawar
One Class To Another Class
Type
Conversion between objects of different classes can be
carried out by either a constructor or a conversion
function.
Choosing of constructor or the conversion function
depends upon where we want the type-conversion
function to be located in the source class or in the
destination class.
continue…
40 By:-Gourav Kottawar
One Class To Another Class
Type
operator typename( )
 Converts the class object of which it is a member to
typename.
 The typename may be a built-in type or a user-defined
one.
 In the case of conversions between objects, typename
refers to the destination class.
 When a class needs to be converted, a casting
operator function can be used at the source class.
 The conversion takes place in the source class and
the result is given to the destination class object.
continue…
41 By:-Gourav Kottawar
One Class To Another Class
Type
Consider a constructor function with a single
argument
 Construction function will be a member of the
destination class.
 The argument belongs to the source class and is
passed to the destination class for conversion.
 The conversion constructor be placed in the
destination class.
continue…
42 By:-Gourav Kottawar

Contenu connexe

Tendances

06. operator overloading
06. operator overloading06. operator overloading
06. operator overloadingHaresh Jaiswal
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++Rabin BK
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Sanjit Shaw
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKumar
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS ConceptBoopathi K
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingabhay singh
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
File handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++Arpita Patel
 
C++ language basic
C++ language basicC++ language basic
C++ language basicWaqar Younis
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsHarsh Patel
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++Ankur Pandey
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading Charndeep Sekhon
 

Tendances (20)

06. operator overloading
06. operator overloading06. operator overloading
06. operator overloading
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
File handling in c
File handling in cFile handling in c
File handling in c
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
C++ language basic
C++ language basicC++ language basic
C++ language basic
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
 
Presentation on overloading
Presentation on overloading Presentation on overloading
Presentation on overloading
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Operator.ppt
Operator.pptOperator.ppt
Operator.ppt
 

Similaire à operator overloading & type conversion in cpp

Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloadingPrincess Sam
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingRai University
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALPrabhu D
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloadingRai University
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
M11 operator overloading and type conversion
M11 operator overloading and type conversionM11 operator overloading and type conversion
M11 operator overloading and type conversionNabeelaNousheen
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfesuEthopi
 
overloading in C++
overloading in C++overloading in C++
overloading in C++Prof Ansari
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basicsgourav kottawar
 
operator overloading
operator overloadingoperator overloading
operator overloadingNishant Joshi
 
Synapse india complain sharing info on chapter 8 operator overloading
Synapse india complain sharing info on chapter 8   operator overloadingSynapse india complain sharing info on chapter 8   operator overloading
Synapse india complain sharing info on chapter 8 operator overloadingSynapseindiaComplaints
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Yaksh Jethva
 
OOPS-Seminar.pdf
OOPS-Seminar.pdfOOPS-Seminar.pdf
OOPS-Seminar.pdfRithiga6
 
Unit3_OOP-converted.pdf
Unit3_OOP-converted.pdfUnit3_OOP-converted.pdf
Unit3_OOP-converted.pdfPowerfullBoy1
 

Similaire à operator overloading & type conversion in cpp (20)

Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
M11 operator overloading and type conversion
M11 operator overloading and type conversionM11 operator overloading and type conversion
M11 operator overloading and type conversion
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
 
overloading in C++
overloading in C++overloading in C++
overloading in C++
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basics
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Synapse india complain sharing info on chapter 8 operator overloading
Synapse india complain sharing info on chapter 8   operator overloadingSynapse india complain sharing info on chapter 8   operator overloading
Synapse india complain sharing info on chapter 8 operator overloading
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)
 
OOPS-Seminar.pdf
OOPS-Seminar.pdfOOPS-Seminar.pdf
OOPS-Seminar.pdf
 
Unit3_OOP-converted.pdf
Unit3_OOP-converted.pdfUnit3_OOP-converted.pdf
Unit3_OOP-converted.pdf
 

Plus de gourav kottawar

constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cppgourav kottawar
 
classes & objects in cpp
classes & objects in cppclasses & objects in cpp
classes & objects in cppgourav kottawar
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overviewgourav kottawar
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cppgourav kottawar
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cppgourav kottawar
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cppgourav kottawar
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overviewgourav kottawar
 
SQL || overview and detailed information about Sql
SQL || overview and detailed information about SqlSQL || overview and detailed information about Sql
SQL || overview and detailed information about Sqlgourav kottawar
 
SQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesSQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesgourav kottawar
 
Rrelational algebra in dbms overview
Rrelational algebra in dbms overviewRrelational algebra in dbms overview
Rrelational algebra in dbms overviewgourav kottawar
 
overview of database concept
overview of database conceptoverview of database concept
overview of database conceptgourav kottawar
 
Relational Model in dbms & sql database
Relational Model in dbms & sql databaseRelational Model in dbms & sql database
Relational Model in dbms & sql databasegourav kottawar
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptgourav kottawar
 
security and privacy in dbms and in sql database
security and privacy in dbms and in sql databasesecurity and privacy in dbms and in sql database
security and privacy in dbms and in sql databasegourav kottawar
 
The system development life cycle (SDLC)
The system development life cycle (SDLC)The system development life cycle (SDLC)
The system development life cycle (SDLC)gourav kottawar
 

Plus de gourav kottawar (20)

constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
classes & objects in cpp
classes & objects in cppclasses & objects in cpp
classes & objects in cpp
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
 
basics of c++
basics of c++basics of c++
basics of c++
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overview
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpp
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cpp
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
basics of c++
basics of c++basics of c++
basics of c++
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
 
SQL || overview and detailed information about Sql
SQL || overview and detailed information about SqlSQL || overview and detailed information about Sql
SQL || overview and detailed information about Sql
 
SQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesSQL querys in detail || Sql query slides
SQL querys in detail || Sql query slides
 
Rrelational algebra in dbms overview
Rrelational algebra in dbms overviewRrelational algebra in dbms overview
Rrelational algebra in dbms overview
 
overview of database concept
overview of database conceptoverview of database concept
overview of database concept
 
Relational Model in dbms & sql database
Relational Model in dbms & sql databaseRelational Model in dbms & sql database
Relational Model in dbms & sql database
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) ppt
 
security and privacy in dbms and in sql database
security and privacy in dbms and in sql databasesecurity and privacy in dbms and in sql database
security and privacy in dbms and in sql database
 
The system development life cycle (SDLC)
The system development life cycle (SDLC)The system development life cycle (SDLC)
The system development life cycle (SDLC)
 

Dernier

Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 

Dernier (20)

Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 

operator overloading & type conversion in cpp

  • 1. Chap 7 Operator Overloading & Type Conversion 1 By:-Gourav Kottawar
  • 2. Contents 7.1 Defining operator Overloading 7.2 Overloading Unary Operator 7.3 Overloading Binary Operator 7.4 Overloading Binary Operator Using Friend function 7.5 Manipulating of String Using Operators 7.6 Type Conversion 7.7 Rules for Overloading Operators 2 By:-Gourav Kottawar
  • 3. Introduction  Important technique allows C++ user defined data types behave in much the same way as built in types.  C++ has ability to provide the operators with a special meanings for a data type.  The mechanism of giving such special meaning to an operator is known as operator overloading. 3 By:-Gourav Kottawar
  • 4. By:-Gourav Kottawar4 Why Operator Overloading?  Readable code  Extension of language to include user-defined types  I.e., classes  Make operators sensitive to context  Generalization of function overloading
  • 5. By:-Gourav Kottawar5 Simple Example class complex { double real, imag; public: complex(double r, double i) : real(r), imag(i) {} }  Would like to be able to write:– complex a = complex(1, 3.0); complex b = complex(1.2, 2); complex c = b; a = b + c; b = b+c*a; c = a*b + complex(1,2); I.e., would like to write ordinary arithmetic expressions on this user-defined class.
  • 6. By:-Gourav Kottawar6 With Operator Overloading, We Can class complex { double real, imag; public: complex(double r, double i) : real(r), imag(i) {} complex operator+(complex a, complex b); complex operator*(complex a, complex b); complex& operator=(complex a, complex b); ... }
  • 7. By:-Gourav Kottawar7 General Format returnType operator*(parameters);    any type keyword operator symbol  Return type may be whatever the operator returns  Including a reference to the object of the operand  Operator symbol may be any overloadable operator from the list.
  • 8. By:-Gourav Kottawar8 C++ Philosophy  All operators have context  Even the simple “built-in” operators of basic types  E.g., '+', '-', '*', '/' for numerical types  Compiler generators different code depending upon type of operands  Operator overloading is a generalization of this feature to non-built-in types  E.g., '<<', '>>' for bit-shift operations and also for stream operations
  • 9. By:-Gourav Kottawar9 C++ Philosophy (continued)  Operators retain their precedence and associativity, even when overloaded  Operators retain their number of operands  Cannot redefine operators on built-in types  Not possible to define new operators  Only (a subset of) the built-in C++ operators can be overloaded
  • 10. Restrictions on Operator Overloading  C++ operators that can be overloaded  C++ Operators that cannot be overloaded Operators that cannot be overloaded . .* :: ?: sizeof Operators that can be overloaded + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete new[] delete[] 10 By:-Gourav Kottawar
  • 11. 7.2 Overloading Unary Operator 11 By:-Gourav Kottawar
  • 12. #include <iostream> using namespace std; class temp { private: int count; public: temp():count(5) { } void operator ++() { count=count+1; } void Display() { cout<<"Count: "<<count; } }; int main() { temp t; ++t; /* operator function void operator ++() is called */ t.Display(); return 0; } 12 By:-Gourav Kottawar
  • 13. #include <iostream> using namespace std; class temp { private: int count; public: temp():count(5) { } void operator ++() { count=count+1; } void Display() { cout<<"Count: "<<count; } }; int main() { temp t; ++t; /* operator function void operator ++() is called */ t.Display(); return 0; } Output Count: 6 13 By:-Gourav Kottawar
  • 14. Note  Operator overloading cannot be used to change the way operator works on built-in types. Operator overloading only allows to redefine the meaning of operator for user-defined types.  There are two operators assignment operator(=) and address operator(&) which does not need to be overloaded. Because these two operators are already overloaded in C++ library. For example: If obj1 and obj2 are two objects of same class then, you can use code obj1=obj2; without overloading = operator. This code will copy the contents object of obj2 to obj1. Similarly, you can use address operator directly without overloading which will return the address of object in memory.  Operator overloading cannot change the precedence 14 By:-Gourav Kottawar
  • 15. 7.3 Overloading Binary Operator #include<iostream.h> #include<conio.h> class complex { int a,b; public: void getvalue() { cout<<"Enter the value of Complex Numbers a,b:"; cin>>a>>b; } complex operator+(complex ob) { complex t; t.a=ob.a +a; t.b=ob.b+b; return(t); } complex operator-(complex ob) { complex t; t.a=ob.a - a; t.b=ob.b -b; return(t); } void display() { cout<<a<<"+"<<b<<"i" <<"n"; } }; 15 By:-Gourav Kottawar
  • 16. void main() { clrscr(); complex obj1,obj2,result,result1; obj1.getvalue(); obj2.getvalue(); result = obj1+obj2; result1=obj1-obj2; cout<<"Input Values:n"; obj1.display(); obj2.display(); cout<<"Result:"; result.display(); result1.display(); getch(); } 16 By:-Gourav Kottawar
  • 17. void main() { clrscr(); complex obj1,obj2,result,result1; obj1.getvalue(); obj2.getvalue(); result = obj1+obj2; result1=obj1-obj2; cout<<"Input Values:n"; obj1.display(); obj2.display(); cout<<"Result:"; result.display(); result1.display(); getch(); } In overloading of binary operators the left hand operand is used to invoke the operator function and the right hand operand is passed as an argument.17 By:-Gourav Kottawar
  • 18. 7.5 Overloading Binary operators using Friend  Friend function can be used to overload binary operator.  Required two arguments to be passed explicitly.#include <iostream> using namespace std; #include <conio.h> class s { public: int i,j; s() { i=j=0;} void disp(){cout << i <<" " << j;} void getdata(){cin>>i>>j;} friend s operator+(int,s); }; s operator+(int a, s s1) { s k; k.i = a+s1.i; k.j = a+s1.j; return k; } int main() { s s2; s2.getdata(); s s3 = 10+s2; s3.disp(); getch(); return 0; }18 By:-Gourav Kottawar
  • 19. #include<iostream.h> class stud { int rno; char *name; int marks; public: friend istream &operator>>(istream &,stud &); friend void operator<<(ostream &,stud &); }; istream &operator>>(istream &tin,stud &s) { cout<<"n Enter the no"; tin>>s.rno; cout<<"n Enter the name"; tin>>s.name; cout<<"n Enter Marks"; tin>>s.marks; return tin; void operator<<(ostream &tout,stud &s) { tout<<”n”<<s.rno; tout<<”n”<<s.name; tout<<”n”<<s.marks; } void main() { cout<<"ttBinaryOperator Overloading Using FriendFunction"; stud s[3]; for(int i=0;i<3;i++) { cin>>s[i]; } for( i=0;i<3;i++) { cout<<s[i]; } getch(); }19 By:-Gourav Kottawar
  • 20. Manipulation of Strings using Operators  There are lot of limitations in string manipulation in C as well as in C++.  Implementation of strings require character arrays, pointers and string functions.  C++ permits us to create our own definitions of operators that can be used to manipulate the strings very much similar to other built-in data types.  ANSI C++ committee has added a new class called string to the C++ class library that supports all kinds of string manipulations.20 By:-Gourav Kottawar
  • 21. Manipulation of Strings using Operators  Strings can be defined as class objects which can be then manipulated like the built-in types.  Since the strings vary in size, we use new to allocate memory for each string and a pointer variable to point to the string array. continue… 21 By:-Gourav Kottawar
  • 22. Manipulation of Strings using Operators  We must create string objects that can hold two pieces of information:  Length  Location class string { char *p; // pointer to string int len; // length of string public : ------ ------ }; continue… 22 By:-Gourav Kottawar
  • 23. // string manipulation #include<iostream.h> #include<string.h> class string { char str[25]; public: void getstring(); void putstring(string&); void display(); string operator+(string&); int operator==(string&); void operator=(string&); void operator+=(string&); }; void string::getstring() { cout<<"Enter string:"; gets(str); } void string::putstring(string &s) { int len=strlen(s.str); cout<<len; } 23 By:-Gourav Kottawar
  • 24. string string::operator+(string &s) { string temp; if((strlen(str)+strlen(s.str))<25) { strcpy(temp.str,s.str); strcat(temp.str,s.str); } else { cout<<endl<<"nconcatenation is not possible"; } return temp; } int string::operator==(string &s) { return(strcmp(str,s.str)==0?1:0) ; } void string::operator=(string &s) { strcpy(str,s.str); } void string::operator+=(string &s) { strcat(str,s.str); } void string::display() { cout<<str; 24 By:-Gourav Kottawar
  • 25. void main() { string s1,s2,s3,s4; clrscr(); s1.getstring(); s2.getstring(); s3=s1+s2; cout<<"nFirst string length="; s1.putstring(s1); cout<<"nSecond string length="; s2.putstring(s2); cout<<endl<<"nConcatenate d string:"; s3.display(); if(s1==s2) cout<<endl<<"nComparison: Equal"; else cout<<endl<<"nComparison: Not equaln"; cout<<endl<<"nafter addition:n"; s1+=s2; s1.display(); s4=s3; cout<<endl<<"copy:"; s4.display(); s1=s2; getch(); 25 By:-Gourav Kottawar
  • 26. Rules For Overloading Operators  Only existing operators can be overloaded. New operators cannot be created.  The overloaded operator must have at least one operand that is of user-defined type.  We cannot change the basic meaning of an operator.  Overloaded operators follow the syntax rules of the original operators. 26 By:-Gourav Kottawar
  • 27. Rules For Overloading Operators  The following operators that cannot be overloaded:  Size of Size of operator  . Membership operator  .* Pointer-to-member operator  : : Scope resolution operator  ? ; Conditional operator continue… 27 By:-Gourav Kottawar
  • 28. Rules For Overloading Operators  The following operators can be over loaded with the use of member functions and not by the use of friend functions:  Assignment operator =  Function call operator( )  Subscripting operator [ ]  Class member access operator ->  Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit values, but, those overloaded by means of a friend function, take one reference argument. continue… 28 By:-Gourav Kottawar
  • 29. Rules For Overloading Operators  Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments.  When using binary operators overloaded through a member function, the left hand operand must be an object of the relevant class.  Binary arithmetic operators such as +, -, * and / must explicitly return a value. They must not attempt to change their own arguments. continue… 29 By:-Gourav Kottawar
  • 30. Type Conversions  The type conversions are automatic only when the data types involved are built-in types. int m; float x = 3.14159; m = x; // convert x to integer before its value is assigned // to m.  For user defined data types, the compiler does not support automatic type conversions.  We must design the conversion routines by ourselves. 30 By:-Gourav Kottawar
  • 31. Type Conversions Different situations of data conversion between incompatible types.  Conversion from basic type to class type.  Conversion from class type to basic type.  Conversion from one class type to another class type. continue… 31 By:-Gourav Kottawar
  • 32. Basic to Class Type A constructor to build a string type object from a char * type variable. string : : string(char *a) { length = strlen(a); P = new char[length+1]; strcpy(P,a); } The variables length and p are data members of the class string. 32 By:-Gourav Kottawar
  • 33. Basic to Class Type string s1, s2; string name1 = “IBM PC”; string name2 = “Apple Computers”; s1 = string(name1); s2 = name2; continue… First converts name1 from char* type to string type and then assigns the string type value to the object s1. First converts name2 from char* type to string type and then assigns the string type value to the object s2. 33 By:-Gourav Kottawar
  • 34. Basic to Class Type class time { int hrs ; int mins ; public : … time (int t) { hrs = t / 60 ; mins = t % 60; } } ; time T1; int duration = 85; T1 = duration; continue… 34 By:-Gourav Kottawar
  • 35. Class To Basic Type A constructor function do not support type conversion from a class type to a basic type. An overloaded casting operator is used to convert a class type data to a basic type. It is also referred to as conversion function. operator typename( ) { … … ( function statements ) … } This function converts a calss type data to typename. 35 By:-Gourav Kottawar
  • 36. Class To Basic Type vector : : operator double( ) { double sum = 0; for (int i=0; i < size ; i++) sum = sum + v[i] * v[i]; return sqrt (sum); } This function converts a vector to the square root of the sum of squares of its components. continue… 36 By:-Gourav Kottawar
  • 37. Class To Basic Type The casting operator function should satisfy the following conditions:  It must be a class member.  It must not specify a return type.  It must not have any arguments. vector : : operator double( ) { double sum = 0; for (int i=0; i < size ; i++) sum = sum + v[i] * v[i]; return sqrt (sum); } continue… 37 By:-Gourav Kottawar
  • 38. Class To Basic Type  Conversion functions are member functions and it is invoked with objects.  Therefore the values used for conversion inside the function belong to the object that invoked the function.  This means that the function does not need an argument. continue… 38 By:-Gourav Kottawar
  • 39. One Class To Another Class Type objX = objY ; // objects of different types  objX is an object of class X and objY is an object of class Y.  The class Y type data is converted to the class X type data and the converted value is assigned to the objX.  Conversion is takes place from class Y to class X.  Y is known as source class.  X is known as destination class. 39 By:-Gourav Kottawar
  • 40. One Class To Another Class Type Conversion between objects of different classes can be carried out by either a constructor or a conversion function. Choosing of constructor or the conversion function depends upon where we want the type-conversion function to be located in the source class or in the destination class. continue… 40 By:-Gourav Kottawar
  • 41. One Class To Another Class Type operator typename( )  Converts the class object of which it is a member to typename.  The typename may be a built-in type or a user-defined one.  In the case of conversions between objects, typename refers to the destination class.  When a class needs to be converted, a casting operator function can be used at the source class.  The conversion takes place in the source class and the result is given to the destination class object. continue… 41 By:-Gourav Kottawar
  • 42. One Class To Another Class Type Consider a constructor function with a single argument  Construction function will be a member of the destination class.  The argument belongs to the source class and is passed to the destination class for conversion.  The conversion constructor be placed in the destination class. continue… 42 By:-Gourav Kottawar