SlideShare a Scribd company logo
MOHIT DADU
Operator Overloading and Scope of Variable
Definition –
Operator overloading is a technique by which operators used in a
programming language are implemented in user-defined types with
customized logic that is based on the types of arguments passed.
What does Operator Overloading mean?
Operator overloading is an important concept in c++. It is a type of
polymorphism in which an operator is overloaded to give user
defined meaning to it.
Operator Overloading and Scope of Variable
OVERLOADABLE/NON-OVERLOADABLE
OPERATORS:
+ - * / % ^
& | ~ ! , =
< > <= >= ++ --
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
Operator Name
. Member selection
.* Pointer-to-member selection
:: Scope resolution
? : Conditional
# Preprocessor convert to string
## Preprocessor concatenate
OPERATOR OVERLOADING EXAMPLES:
OPERATORS AND EXAMPLE
Unary operators overloading
Binary operators overloading
Relational operators overloading
Input / Output operators overloading
++ and -- operators overloading
Assignment operators overloading
Function call () operator overloading
Subscripting [] operator overloading
Class member access operator -> overloading
! (logicalNOT)
& (address-of)
~ (one's complement)
* (pointerdereference)
+ (unary plus)
- (unarynegation)
++ (increment)
-- (decrement)
OVERLOADING UNARY OPERATORS:
Binary Operators
*= Multiplication/assignment
+= Addition/assignment
–= Subtraction/assignment
–> Member selection
–>* Pointer-to-member selection
/= Division/assignment
Operator Name
!= Inequality
% Modulus
%= Modulus/assignment
&& Logical AND
&= Bitwise AND/assignment
<< Left shift
<<= Left shift/assignment
<= Less than or equal to
== Equality
>= Greater than or equal to
>> Right shift
>>= Right shift/assignment
^= Exclusive OR/assignment
|= Bitwise inclusive OR/assignment
|| Logical OR
 The operators :: (scope resolution), . (member access), .* (member access
through pointer to member), and ?:(ternary conditional) cannot be overloaded
 New operators such as **, < >, or & | cannot be created.
 The overloads of operators &&, ||, and , (comma) lose their special
properties: short-circuit evaluation and sequencing.
 The overload of operator -> must either return a raw pointer or return an
object (by reference or by value), for which operator -> is in turn overloaded.
 Precedence and Associativity of an operator cannot be changed.
 Cannot redefine the meaning of a procedure.
Restrictions:
To overload a operator, a operator
function is defined inside a class as:
The return type comes first which is
followed by keyword operator, followed
by operator sign,i.e., the operator you
want to overload like: +, <, ++ etc. and
finally the arguments is passed. Then,
inside the body of you want perform the
task you want when this operator function
is called.
How to overload operators in C++ programming?
Example of operator overloading in C++ Programming
#include <iostream.h>
class temp {
private:
int count;
public:
temp(): count(5){ }
void operator ++()
{ count=count+1; }
void Display()
{ cout<<"Count: "<<count;
}
};
OUTPUT
Count: 6
int main()
{ temp t;
++t; //operator function void
operator ++() is called
Display();
return 0;
}
Operator Overloading and Scope of Variable
SCOPE OFVARIABLES:-
Scopeof variableis definedas region or part of program in which
the variableis visible/ accessed/ valid .
all the variablehavetheir area of functioningand out of that boundarythey don’t hold
their value, this boundaryis calledscopeof the variable.
Types of Scope OfVariable :-
1. Global scope.
2. Local Scope.
Globalvariablearethose,whichareonce
declaredandcanbeusedthroughoutthe
lifetimeof theprogrambyanyclassor
anyfunction.
theycanbe assigneddifferentvaluesat
differenttimeinprogramlifetime.But
eveniftheyaredeclaredandinitializein
thesametimeoutsidethemainfunction,
thenalsotheycanbeassignedanyvalue
atanypointintotheprogram.
GLOBAL VARIABLE:
Variable is said to have global scope / file scope if it is defined outside
the function and whose visibility is entire program.
 File Scope is also called Global Scope.
 It can be used outside the function or a block.
 It is visible in entire program.
 Variables defined within Global scope is called as Global variables.
Variable declared globally is said to having program scope.
 A variable declared globally with static keyword is said to have file
scope.
.
File Scope of Variable :
For example:
#include<iostream.h>
int x = 0; // **program scope**
static int y = 0; // **file scope**
static float z = 0.0; // **file scope**
int main()
{
int i; /* block scope */
/*
.
.
.
*/
return 0;
}
Advantages / Disadvantages of File scope / Global
Variable
Advantages of Global Variables :
If some common data needed to all functions can be declared as global to avoid
the parameter passing
Any changes made in any function can be used / accessed by other
Disadvantages of Global Variables :
Too many variables , if declared as global , then they remain in the memory till
program execution is over
Unprotected data : Data can be modified by any function
Localvariablearethevariableswhich
existonlybetweenthecurlybraces,in
whichitsdeclared.outsidewhichtheyare
unavailableandleadstocompiletime
error.
Variablesthataredeclaredinsidea
functionorblockarelocalvariables.They
canbeusedonlybystatementsthatare
insidethatfunctionorblockofcode.Local
variablesarenotknowntofunctions
outsidetheirown.Followingisthe
exampleusinglocalvariables:
LOCAL VARIABLE
Block Scope of Variable :
Block Scope i.e Local Scope of variable is used to evaluate expression at block
level. Variable is said to have local scope / block scope if it is defined within
function or local block. In short we can say that local variables are in block scope..
Important Points About Block Scope :
 Block Scope is also called Local Scope
 It can be used only within a function or a block
 It is not visible outside the block
 Variables defined within local scope is called as Local variables
Example : Block/Local Scope
#include<stdio.h>
void message();
void main()
{
int num1 = 0 ; // Local to main
printf("%d",num1);
message();
}
void message()
{
int num1 = 1 ; // Local to Function message
printf("%d",num1);
}
Output:
0 1
• In both the functions main() and message() we have declared same
variable.Since these two functions are having different block/local scope,
compiler will not throw compile error.
• Whenever our control is in main() function we have access to variable from
main() function only. Thus 0 will be printed inside main() function.
• As soon as control goes inside message() function , Local copy of main is no
longer accessible. Since we have re-declared same variable inside message()
function, we can access variable local to message(). “1” will be printed on the
screen.
Explanation Of Code :
Example 2:
#include<iostream.h>
void message();
void main()
{
int num1 = 6 ;
Cout<<num1;
message();
}
void message()
{
cout<<num1;
}
Compile error:
Variable num1 is visible only with
in main function, it can not be
accessed by other function.
Output of Above Program :
Advantages / Disadvantages of Local scope / Block
Variable
Advantages of Local Variables :
 Since data cannot be accessed from other functions , Data Integrity is preserved.
 Only required data can be passed to function , thus protecting the remaining data.
Disadvantages of Local Variables :
 Common data required to pass again and again .
 They have Limited scope.
Class scope:
The scope of the class either global or local.
Global Class:
A class is said to be global class if its definition occur outside the
class if the definition occur outside the bodies of all function in a
program
which means that object of this class type can be declared from
anywhere in the program.
For instance consider the following code fragment:
#include<iostream.h>
class X Global class type X
{ :
:
};
X obj1; Global object obj1 of type X
Int main()
{
X obj2; Local object obj2 of type X
:
}
Void function(void)
{
X obj3; Local object obj3 of type X
:
}
Example:
A class is said to be local class if its definition occur inside a function body, which
means that the object of this class type can be declared only within the function that
define this class type.
#include<iostream,h>
Int main()
{
Class Y Local class type Y
{ :
};
Y obj1; Local object obj1 of type X
}
Void function(void)
{
Y obj2; invalid. Y type is not available in function().
:
}
Local Class :
Global Object:
#include<iostream.h>
classx
{
:
public:
inta;
voidfun();
};
xobj1;
int main()
{
obj1.a=10;
obj1.fun();
}
void fun2(void)
{
obj.a=20;
obj1.fun();
}
NOTE :
A global object can only be
declared using global class type
NOTE:
A local object can be created from
both class types: global as well as local.
Local Object:
#include<iostream.h>
class x
{
public:
int a;
void fun( );
};
void main( )
{
x obj1;
obj1.a=10;
obj1.fun( );
}
THANK
YOU

More Related Content

PPTX
Functions in C
PDF
Lecture20 user definedfunctions.ppt
PDF
Function in C++
PPTX
Function overloading and overriding
DOC
4. function
PPTX
Functions in c
PPTX
predefined and user defined functions
PPTX
Functions in C
Functions in C
Lecture20 user definedfunctions.ppt
Function in C++
Function overloading and overriding
4. function
Functions in c
predefined and user defined functions
Functions in C

What's hot (20)

PDF
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
PDF
Class and object
PPT
user defined function
PPTX
Function & Recursion
PPTX
Functions in c language
PPT
Basic structure of C++ program
PPTX
Functions in Python
PDF
VIT351 Software Development VI Unit1
PPTX
Function C programming
PPT
08 c++ Operator Overloading.ppt
PPT
C by balaguruswami - e.balagurusamy
PPTX
Function Parameters
PDF
Programming Fundamentals Functions in C and types
PDF
Lecture21 categoriesof userdefinedfunctions.ppt
PPTX
Recursive Function
PPSX
Object oriented concepts & programming (2620003)
PPT
User defined functions in C programmig
PPTX
Functions in python
PPTX
Functions in python slide share
PPT
Functions in c
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
Class and object
user defined function
Function & Recursion
Functions in c language
Basic structure of C++ program
Functions in Python
VIT351 Software Development VI Unit1
Function C programming
08 c++ Operator Overloading.ppt
C by balaguruswami - e.balagurusamy
Function Parameters
Programming Fundamentals Functions in C and types
Lecture21 categoriesof userdefinedfunctions.ppt
Recursive Function
Object oriented concepts & programming (2620003)
User defined functions in C programmig
Functions in python
Functions in python slide share
Functions in c
Ad

Viewers also liked (19)

PPT
Operator Overloading
PDF
Scope of variables
PDF
Operator overloading in C++
PPT
Operator overloading
PDF
Logic programming (1)
PPT
Logic Programming and Prolog
PPTX
protocols of concurrency control
PPTX
operator overloading & type conversion in cpp over view || c++
PPTX
Critical section problem in operating system.
PPT
Context Aware Computing
PPTX
Variable scope
PPTX
Operating system critical section
PDF
Logic Programming and ILP
PDF
[Whitepaper] Cisco Vision: 5G - THRIVING INDOORS
PPTX
Power Supply
PPTX
Online Quiz System Project PPT
PPTX
Bca 2nd sem u-4 operator overloading
PPTX
operator overloading in c++
PPTX
Online examination system
Operator Overloading
Scope of variables
Operator overloading in C++
Operator overloading
Logic programming (1)
Logic Programming and Prolog
protocols of concurrency control
operator overloading & type conversion in cpp over view || c++
Critical section problem in operating system.
Context Aware Computing
Variable scope
Operating system critical section
Logic Programming and ILP
[Whitepaper] Cisco Vision: 5G - THRIVING INDOORS
Power Supply
Online Quiz System Project PPT
Bca 2nd sem u-4 operator overloading
operator overloading in c++
Online examination system
Ad

Similar to Operator Overloading and Scope of Variable (20)

PPT
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
PPT
Chapter Introduction to Modular Programming.ppt
PDF
Chapter 11 Function
PPTX
FUNCTION CPU
PPTX
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
PPT
Lec 28 - operator overloading
PDF
Data structure scope of variables
PPT
POLITEKNIK MALAYSIA
DOCX
Functions assignment
DOC
What is storage class
PDF
3-Python Functions.pdf in simple.........
PPTX
Chapter One Function.pptx
PPTX
04. WORKING WITH FUNCTIONS-2 (1).pptx
PPT
Lec 26.27-operator overloading
PDF
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
PPT
Basics of cpp
DOC
Basic construction of c
PPT
arrays.ppt
PPTX
Interoduction to c++
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
Chapter Introduction to Modular Programming.ppt
Chapter 11 Function
FUNCTION CPU
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
Lec 28 - operator overloading
Data structure scope of variables
POLITEKNIK MALAYSIA
Functions assignment
What is storage class
3-Python Functions.pdf in simple.........
Chapter One Function.pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
Lec 26.27-operator overloading
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
Basics of cpp
Basic construction of c
arrays.ppt
Interoduction to c++

Operator Overloading and Scope of Variable

  • 3. Definition – Operator overloading is a technique by which operators used in a programming language are implemented in user-defined types with customized logic that is based on the types of arguments passed. What does Operator Overloading mean? Operator overloading is an important concept in c++. It is a type of polymorphism in which an operator is overloaded to give user defined meaning to it.
  • 5. OVERLOADABLE/NON-OVERLOADABLE OPERATORS: + - * / % ^ & | ~ ! , = < > <= >= ++ -- << >> == != && || += -= /= %= ^= &= |= *= <<= >>= [] ()
  • 6. Operator Name . Member selection .* Pointer-to-member selection :: Scope resolution ? : Conditional # Preprocessor convert to string ## Preprocessor concatenate
  • 7. OPERATOR OVERLOADING EXAMPLES: OPERATORS AND EXAMPLE Unary operators overloading Binary operators overloading Relational operators overloading Input / Output operators overloading ++ and -- operators overloading Assignment operators overloading Function call () operator overloading Subscripting [] operator overloading Class member access operator -> overloading
  • 8. ! (logicalNOT) & (address-of) ~ (one's complement) * (pointerdereference) + (unary plus) - (unarynegation) ++ (increment) -- (decrement) OVERLOADING UNARY OPERATORS:
  • 9. Binary Operators *= Multiplication/assignment += Addition/assignment –= Subtraction/assignment –> Member selection –>* Pointer-to-member selection /= Division/assignment Operator Name != Inequality % Modulus %= Modulus/assignment && Logical AND &= Bitwise AND/assignment
  • 10. << Left shift <<= Left shift/assignment <= Less than or equal to == Equality >= Greater than or equal to >> Right shift >>= Right shift/assignment ^= Exclusive OR/assignment |= Bitwise inclusive OR/assignment || Logical OR
  • 11.  The operators :: (scope resolution), . (member access), .* (member access through pointer to member), and ?:(ternary conditional) cannot be overloaded  New operators such as **, < >, or & | cannot be created.  The overloads of operators &&, ||, and , (comma) lose their special properties: short-circuit evaluation and sequencing.  The overload of operator -> must either return a raw pointer or return an object (by reference or by value), for which operator -> is in turn overloaded.  Precedence and Associativity of an operator cannot be changed.  Cannot redefine the meaning of a procedure. Restrictions:
  • 12. To overload a operator, a operator function is defined inside a class as: The return type comes first which is followed by keyword operator, followed by operator sign,i.e., the operator you want to overload like: +, <, ++ etc. and finally the arguments is passed. Then, inside the body of you want perform the task you want when this operator function is called. How to overload operators in C++ programming?
  • 13. Example of operator overloading in C++ Programming #include <iostream.h> class temp { private: int count; public: temp(): count(5){ } void operator ++() { count=count+1; } void Display() { cout<<"Count: "<<count; } }; OUTPUT Count: 6 int main() { temp t; ++t; //operator function void operator ++() is called Display(); return 0; }
  • 15. SCOPE OFVARIABLES:- Scopeof variableis definedas region or part of program in which the variableis visible/ accessed/ valid . all the variablehavetheir area of functioningand out of that boundarythey don’t hold their value, this boundaryis calledscopeof the variable. Types of Scope OfVariable :- 1. Global scope. 2. Local Scope.
  • 17. Variable is said to have global scope / file scope if it is defined outside the function and whose visibility is entire program.  File Scope is also called Global Scope.  It can be used outside the function or a block.  It is visible in entire program.  Variables defined within Global scope is called as Global variables. Variable declared globally is said to having program scope.  A variable declared globally with static keyword is said to have file scope. . File Scope of Variable :
  • 18. For example: #include<iostream.h> int x = 0; // **program scope** static int y = 0; // **file scope** static float z = 0.0; // **file scope** int main() { int i; /* block scope */ /* . . . */ return 0; }
  • 19. Advantages / Disadvantages of File scope / Global Variable Advantages of Global Variables : If some common data needed to all functions can be declared as global to avoid the parameter passing Any changes made in any function can be used / accessed by other Disadvantages of Global Variables : Too many variables , if declared as global , then they remain in the memory till program execution is over Unprotected data : Data can be modified by any function
  • 21. Block Scope of Variable : Block Scope i.e Local Scope of variable is used to evaluate expression at block level. Variable is said to have local scope / block scope if it is defined within function or local block. In short we can say that local variables are in block scope.. Important Points About Block Scope :  Block Scope is also called Local Scope  It can be used only within a function or a block  It is not visible outside the block  Variables defined within local scope is called as Local variables
  • 22. Example : Block/Local Scope #include<stdio.h> void message(); void main() { int num1 = 0 ; // Local to main printf("%d",num1); message(); } void message() { int num1 = 1 ; // Local to Function message printf("%d",num1); } Output: 0 1
  • 23. • In both the functions main() and message() we have declared same variable.Since these two functions are having different block/local scope, compiler will not throw compile error. • Whenever our control is in main() function we have access to variable from main() function only. Thus 0 will be printed inside main() function. • As soon as control goes inside message() function , Local copy of main is no longer accessible. Since we have re-declared same variable inside message() function, we can access variable local to message(). “1” will be printed on the screen. Explanation Of Code :
  • 24. Example 2: #include<iostream.h> void message(); void main() { int num1 = 6 ; Cout<<num1; message(); } void message() { cout<<num1; } Compile error: Variable num1 is visible only with in main function, it can not be accessed by other function. Output of Above Program :
  • 25. Advantages / Disadvantages of Local scope / Block Variable Advantages of Local Variables :  Since data cannot be accessed from other functions , Data Integrity is preserved.  Only required data can be passed to function , thus protecting the remaining data. Disadvantages of Local Variables :  Common data required to pass again and again .  They have Limited scope.
  • 26. Class scope: The scope of the class either global or local. Global Class: A class is said to be global class if its definition occur outside the class if the definition occur outside the bodies of all function in a program which means that object of this class type can be declared from anywhere in the program. For instance consider the following code fragment:
  • 27. #include<iostream.h> class X Global class type X { : : }; X obj1; Global object obj1 of type X Int main() { X obj2; Local object obj2 of type X : } Void function(void) { X obj3; Local object obj3 of type X : } Example:
  • 28. A class is said to be local class if its definition occur inside a function body, which means that the object of this class type can be declared only within the function that define this class type. #include<iostream,h> Int main() { Class Y Local class type Y { : }; Y obj1; Local object obj1 of type X } Void function(void) { Y obj2; invalid. Y type is not available in function(). : } Local Class :
  • 29. Global Object: #include<iostream.h> classx { : public: inta; voidfun(); }; xobj1; int main() { obj1.a=10; obj1.fun(); } void fun2(void) { obj.a=20; obj1.fun(); } NOTE : A global object can only be declared using global class type
  • 30. NOTE: A local object can be created from both class types: global as well as local. Local Object: #include<iostream.h> class x { public: int a; void fun( ); }; void main( ) { x obj1; obj1.a=10; obj1.fun( ); }