SlideShare una empresa de Scribd logo
1 de 31
MOHIT DADU
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.
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;
}
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

Más contenido relacionado

La actualidad más candente

FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)Mansi Tyagi
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Basic structure of C++ program
Basic structure of C++ programBasic structure of C++ program
Basic structure of C++ programmatiur rahman
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1YOGESH SINGH
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
 
Lecture21 categoriesof userdefinedfunctions.ppt
Lecture21 categoriesof userdefinedfunctions.pptLecture21 categoriesof userdefinedfunctions.ppt
Lecture21 categoriesof userdefinedfunctions.ppteShikshak
 
Recursive Function
Recursive FunctionRecursive Function
Recursive FunctionHarsh Pathak
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)nirajmandaliya
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmigAppili Vamsi Krishna
 
Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 

La actualidad más candente (20)

FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
 
Class and object
Class and objectClass and object
Class and object
 
user defined function
user defined functionuser defined function
user defined function
 
Function & Recursion
Function & RecursionFunction & Recursion
Function & Recursion
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Basic structure of C++ program
Basic structure of C++ programBasic structure of C++ program
Basic structure of C++ program
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
Function Parameters
Function ParametersFunction Parameters
Function Parameters
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Lecture21 categoriesof userdefinedfunctions.ppt
Lecture21 categoriesof userdefinedfunctions.pptLecture21 categoriesof userdefinedfunctions.ppt
Lecture21 categoriesof userdefinedfunctions.ppt
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Functions in c
Functions in cFunctions in c
Functions in c
 

Destacado

Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++Ilio Catallo
 
Logic programming (1)
Logic programming (1)Logic programming (1)
Logic programming (1)Nitesh Singh
 
Logic Programming and Prolog
Logic Programming and PrologLogic Programming and Prolog
Logic Programming and PrologSadegh Dorri N.
 
protocols of concurrency control
protocols of concurrency controlprotocols of concurrency control
protocols of concurrency controlMOHIT DADU
 
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
 
Critical section problem in operating system.
Critical section problem in operating system.Critical section problem in operating system.
Critical section problem in operating system.MOHIT DADU
 
Context Aware Computing
Context Aware ComputingContext Aware Computing
Context Aware ComputingMOHIT DADU
 
[Whitepaper] Cisco Vision: 5G - THRIVING INDOORS
[Whitepaper] Cisco Vision: 5G - THRIVING INDOORS[Whitepaper] Cisco Vision: 5G - THRIVING INDOORS
[Whitepaper] Cisco Vision: 5G - THRIVING INDOORSCisco Service Provider
 
Online Quiz System Project PPT
Online Quiz System Project PPTOnline Quiz System Project PPT
Online Quiz System Project PPTShanthan Reddy
 
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
 
operator overloading in c++
operator overloading in c++operator overloading in c++
operator overloading in c++harman kaur
 
Online examination system
Online examination systemOnline examination system
Online examination systemAj Maurya
 

Destacado (19)

Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Scope of variables
Scope of variablesScope of variables
Scope of variables
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++
 
Operator overloading
Operator overloading Operator overloading
Operator overloading
 
Logic programming (1)
Logic programming (1)Logic programming (1)
Logic programming (1)
 
Logic Programming and Prolog
Logic Programming and PrologLogic Programming and Prolog
Logic Programming and Prolog
 
protocols of concurrency control
protocols of concurrency controlprotocols of concurrency control
protocols of concurrency control
 
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++
 
Critical section problem in operating system.
Critical section problem in operating system.Critical section problem in operating system.
Critical section problem in operating system.
 
Context Aware Computing
Context Aware ComputingContext Aware Computing
Context Aware Computing
 
Variable scope
Variable scopeVariable scope
Variable scope
 
Operating system critical section
Operating system   critical sectionOperating system   critical section
Operating system critical section
 
Logic Programming and ILP
Logic Programming and ILPLogic Programming and ILP
Logic Programming and ILP
 
[Whitepaper] Cisco Vision: 5G - THRIVING INDOORS
[Whitepaper] Cisco Vision: 5G - THRIVING INDOORS[Whitepaper] Cisco Vision: 5G - THRIVING INDOORS
[Whitepaper] Cisco Vision: 5G - THRIVING INDOORS
 
Power Supply
Power SupplyPower Supply
Power Supply
 
Online Quiz System Project PPT
Online Quiz System Project PPTOnline Quiz System Project PPT
Online Quiz System Project PPT
 
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
 
operator overloading in c++
operator overloading in c++operator overloading in c++
operator overloading in c++
 
Online examination system
Online examination systemOnline examination system
Online examination system
 

Similar a Operator Overloading and Scope of Variable

Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptAmanuelZewdie4
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxSangeetaBorde3
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloadingPrincess Sam
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variablesSaurav Kumar
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignmentAhmad Kamal
 
What is storage class
What is storage classWhat is storage class
What is storage classIsha Aggarwal
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptxmiki304759
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptxManas40552
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of ckinish kumar
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++Amresh Raj
 

Similar a Operator Overloading and Scope of Variable (20)

Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
C functions list
C functions listC functions list
C functions list
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignment
 
What is storage class
What is storage classWhat is storage class
What is storage class
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 
Functions
Functions Functions
Functions
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 

Operator Overloading and Scope of Variable

  • 2.
  • 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.
  • 4.
  • 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; }
  • 14.
  • 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( ); }