Unary Operators Unary Operators http://ecomputernotes.com
Unary OperatorsUnary Operators
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Unary operators are usually prefix, except Unary operators are usually prefix, except for for ++++ and and ----
►►++++ andand ---- both act as prefix and postfixboth act as prefix and postfix
►►Example:Example:
�� h++;h++;
�� gg---- + ++h + ++h -- ----i;i;
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Behavior of ++ and Behavior of ++ and ---- for prefor pre--defined types:defined types:
��PostPost--increment increment ++:++:
►►PostPost--increment operator ++ increments increment operator ++ increments the current value and then returns the the current value and then returns the previous valueprevious value
��PostPost--decrement decrement ----::
►►Works exactly like post ++Works exactly like post ++
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Example:Example:intint x = 1, y = 2;x = 1, y = 2;
coutcout << y++ << << y++ << endlendl;;
coutcout << y;<< y;
►►Output:Output:22
33http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Example:Example:intint y = 2;y = 2;
y++++;y++++; // Error// Error
y++ = x; y++ = x; // Error// Error
Post-increment ++
returns by value,
hence an error while
assignment
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Behavior of ++ and Behavior of ++ and ---- for prefor pre--
defined types:defined types:
��PrePre--increment increment ++:++:
►►PrePre--increment operator ++ increments the increment operator ++ increments the
current value and then returns itcurrent value and then returns it’’s references reference
��PrePre--decrement decrement ----::
►►Works exactly like PreWorks exactly like Pre--increment ++increment ++
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Example:Example:intint y = 2;y = 2;
coutcout << ++y << << ++y << endlendl;;
coutcout << y << << y << endlendl;;
►►Output:Output:33
33http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Example:Example:intint x = 2, y = 2;x = 2, y = 2;
++++y;++++y;
coutcout << y;<< y;
++y = x;++y = x;
coutcout << y;<< y;
►►Output:Output:44
22
Pre-increment ++
returns by
reference, hence
NOT an error
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Example (PreExample (Pre--increment):increment):
class Complex{class Complex{
double real, double real, imgimg;;
public:public:
......
Complex & operator ++ ();Complex & operator ++ ();
// friend Complex & operator //// friend Complex & operator //++(Complex &);++(Complex &);
}}http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Member function definition:Member function definition:
Complex & Complex & Complex::operatorComplex::operator++(){++(){
real = real = realreal + 1;+ 1;
return * this;return * this;
}}
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Friend function definition:Friend function definition:
Complex & operator ++ (Complex Complex & operator ++ (Complex & h){& h){
h.realh.real += 1;+= 1;
return h;return h;
}}
http://ecomputernotes.com
Unary OperatorsUnary Operators
Complex h1, h2, h3;Complex h1, h2, h3;
++h1;++h1;
►►Function Function operator++()operator++() returns a returns a reference so that the object can be used reference so that the object can be used as an as an lvaluelvalue
++h1 = h2 + ++h3;++h1 = h2 + ++h3;
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►How does a compiler know How does a compiler know whether it is a prewhether it is a pre--increment or increment or a posta post--increment ?increment ?
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►A postA post--fix unary operator is fix unary operator is
implemented using:implemented using:
Member function with 1 dummy Member function with 1 dummy intint
argumentargument
OROR
NonNon--member function with two argumentsmember function with two arguments
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►In post increment, current value of the In post increment, current value of the
object is stored in a temporary variableobject is stored in a temporary variable
►►Current object is incrementedCurrent object is incremented
►►Value of the temporary variable is Value of the temporary variable is returnedreturned
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►PostPost--increment operator:increment operator:
class Complex{class Complex{
......
Complex operator ++ (Complex operator ++ (intint););
// friend Complex operator //// friend Complex operator //++(const Complex &, ++(const Complex &, intint););
}}
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Member function definition:Member function definition:
Complex Complex Complex::operatorComplex::operator ++ ++ ((intint){){
complex t = *this;complex t = *this;
real += 1;real += 1;
return t;return t;
}}
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►Friend function definition:Friend function definition:
Complex operator ++ (const Complex operator ++ (const
Complex & h, Complex & h, intint){){
complex t = h; complex t = h;
h.realh.real += 1;+= 1;
return t;return t;
}}http://ecomputernotes.com
Unary OperatorsUnary Operators
►►The dummy parameter in the operator The dummy parameter in the operator function tells compiler that it is postfunction tells compiler that it is post--incrementincrement
►►Example:Example:
Complex h1, h2, h3;Complex h1, h2, h3;
h1++;h1++;
h3++ = h2 + h3++; // Errorh3++ = h2 + h3++; // Error……
http://ecomputernotes.com
Unary OperatorsUnary Operators
►►The The prepre and and postpost decrement decrement operator operator ---- is implemented in is implemented in exactly the same wayexactly the same way
http://ecomputernotes.com
Type ConversionType Conversion
►►The compiler automatically performs a The compiler automatically performs a
type coercion of compatible typestype coercion of compatible types
►►e.ge.g::
intint f = 0.021;f = 0.021;
double g = 34;double g = 34;
// type // type floatfloat is automatically converted // is automatically converted // into into intint. Compiler only issues a // . Compiler only issues a //
warningwarning……
Type ConversionType Conversion
►►The user can also explicitly convert The user can also explicitly convert
between types:between types:
intint g = (int)0.0210;g = (int)0.0210;
double h = double(35);double h = double(35);
// type // type floatfloat is explicitly converted // is explicitly converted // ((castedcasted) into ) into intint. Not even a warning // is . Not even a warning // is
issued nowissued now……
C style type
casting
Type ConversionType Conversion
►►For user defined classes, there are two For user defined classes, there are two
types of conversionstypes of conversions
��From any other type to current typeFrom any other type to current type
��From current type to any other typeFrom current type to any other type
http://ecomputernotes.com
Type ConversionType Conversion
►►Conversion from any other type to Conversion from any other type to
current type:current type:
��Requires a constructor with a single Requires a constructor with a single
parameterparameter
►►Conversion from current type to any Conversion from current type to any
other type:other type:
��Requires an overloaded operatorRequires an overloaded operator
Type ConversionType Conversion
►►Conversion from other type to current Conversion from other type to current type (type (intint to to StringString):):
class String{class String{
......
public:public:
String(intString(int a);a);
char * char * GetStringPtr()constGetStringPtr()const;;
};};
Type ConversionType Conversion
String::String(intString::String(int a){a){
coutcout << << ""String(intString(int) called...") called..." << << endlendl;;
char array[15];char array[15];
itoa(aitoa(a, array, 10);, array, 10);
size = size = strlen(arraystrlen(array););
bufferPtrbufferPtr = new char [size + 1];= new char [size + 1];
strcpy(bufferPtrstrcpy(bufferPtr, array);, array);
}}
char * char * String::GetStringPtrString::GetStringPtr() const{() const{
return return bufferPtrbufferPtr;;
}} http://ecomputernotes.com
Type ConversionType Conversion
intint main(){main(){
String s = 345;String s = 345;
coutcout << << s.GetStringPtrs.GetStringPtr() << () << endlendl;;
return 0;return 0;
}}
http://ecomputernotes.com
Type ConversionType Conversion
►►Output:Output:
String(intString(int) called) called……
345345
http://ecomputernotes.com
Type ConversionType Conversion
►►Automatic conversion has drawbacksAutomatic conversion has drawbacks
►►Conversion takes place transparently Conversion takes place transparently
even if the user didneven if the user didn’’t wanted the t wanted the
conversionconversion
http://ecomputernotes.com
Type ConversionType Conversion
User can write the following code to initialize the User can write the following code to initialize the string with a single character:string with a single character:
intint main(){main(){
String s = String s = ‘‘AA’’;;
coutcout << << s.GetStringPtrs.GetStringPtr()<< ()<< endlendl
<< << s.GetSizes.GetSize()() << << endlendl;;
return 0;return 0;
}}http://ecomputernotes.com
Type ConversionType Conversion
►►Output:Output:
String(intString(int) called) called……
6565
22
ASCII code
for ‘A’ !!!
String size is
also 2
instead of 1
Type ConversionType Conversion
There is a mechanism in C++ to restrict There is a mechanism in C++ to restrict
automatic conversionsautomatic conversions
►►Keyword Keyword explicitexplicit
►►Casting must be explicitly performed by Casting must be explicitly performed by
the userthe user
http://ecomputernotes.com
Type ConversionType Conversion
►►Keyword Keyword explicit explicit only works with only works with constructors constructors
►►Example:Example:class String{class String{
……
public:public:
……
explicit explicit String(intString(int););
};};http://ecomputernotes.com
Type ConversionType Conversion
intint main(){main(){
String s;String s;
// Error// Error……
s = s = ‘‘AA’’;;
return 0;return 0;
}}http://ecomputernotes.com
Type ConversionType Conversion
intint main(){main(){
String s1, s2;String s1, s2;
// valid, explicit casting// valid, explicit casting……
s1 = String(101);s1 = String(101);
// OR// OR
s2 = (String)204;s2 = (String)204;
return 0;return 0;
}} http://ecomputernotes.com
Type ConversionType Conversion
►►There is another method for type There is another method for type
conversion:conversion:
““Operator overloadingOperator overloading””
((Converting from current type to any Converting from current type to any other typeother type))
http://ecomputernotes.com
Type ConversionType Conversion
►►General Syntax:General Syntax:TYPETYPE11::Operator TYPE::Operator TYPE22();();
►►Must be a member functionMust be a member function
►►NO return type and arguments are NO return type and arguments are specifiedspecified
►►Return type is implicitly taken to be Return type is implicitly taken to be TYPETYPE22 by compilerby compiler
Type ConversionType Conversion
►►Overloading preOverloading pre--defined types:defined types:
class String{class String{
……
public:public:
……
operator operator intint();();
operator char *();operator char *();
};};http://ecomputernotes.com
Type ConversionType Conversion
String::operatorString::operator intint(){(){
if(sizeif(size > 0)> 0)
return return atoi(bufferPtratoi(bufferPtr););
elseelse
return return --1;1;
}}
http://ecomputernotes.com
Type ConversionType Conversion
String::operatorString::operator char *(){char *(){
return return bufferPtrbufferPtr;;
}}
http://ecomputernotes.com
Type ConversionType Conversion
intint main(){main(){
String s("2324");String s("2324");
coutcout << (<< (int)sint)s << << endlendl
<< (char *)s;<< (char *)s;
return 0;return 0;
}}
http://ecomputernotes.com
Type ConversionType Conversion
Output:Output:23242324
23242324
http://ecomputernotes.com
Type ConversionType Conversion
►►UserUser--defined types can be overloaded in defined types can be overloaded in exactly the same wayexactly the same way
►►Only prototype is shown below:Only prototype is shown below:class String{class String{
……
operator Complex();operator Complex();
operator operator HugeIntHugeInt();();
operator operator IntVectorIntVector();();
};};http://ecomputernotes.com
Type ConversionType Conversion
►►Modifying String class:Modifying String class:
class String{class String{
……
public:public:
……
String(charString(char *);*);
operator operator intint();();
};};http://ecomputernotes.com
Type ConversionType Conversion
intint main(){main(){
String String s(s(““FakhirFakhir");");
// << is NOT overloaded// << is NOT overloaded
coutcout << s;<< s;
return 0;return 0;
}}
http://ecomputernotes.com
Type ConversionType Conversion
Output:Output:Junk ReturnedJunk Returned……
http://ecomputernotes.com
Type ConversionType Conversion
►►Modifying String class:Modifying String class:
class String{class String{
……
public:public:
……
String(charString(char *);*);
intint AsIntAsInt();();
};};http://ecomputernotes.com
Type ConversionType Conversion
intint String::AsIntString::AsInt(){(){
if(sizeif(size > 0)> 0)
return return atoi(bufferPtratoi(bufferPtr););
elseelse
return return --1;1;
}}
http://ecomputernotes.com
Type ConversionType Conversion
intint main(){main(){
String s(String s(““434");434");
// << is NOT overloaded// << is NOT overloaded
coutcout << s; << s; //error//error
coutcout << << s.AsInts.AsInt();();
return 0;return 0;
}}
http://ecomputernotes.com