Scope Resolution operator in C++ :-
Visibility or availability of a variable in a program is called as scope. There are two types of scope. i) Local scope ii) Global scope.
Local scope:- visibility of a variable is local to the function in which it is declared.
Global scope:- visibility of a variable to all functions of a program.
Scope resolution operator in "::"
This is used to access global variables if same variables are declared as local and global .
Example:-
int a=5;
void main()
{
cout<<"Local a="<<endl;
cout<<"Global a="<<endl;
}
Class scope:-
Scope resolution operator(::) is used to define a function outside a class.
Example:-
#include<iostream.h>
#include<conio.h>
class sample
{
public:
void output();
};
class void sample::output()
{
cout<<"Function defined outside the class:/n";
};
int main()
{
sample obj;
obj.output();
return 0;
}
Output:-
Function defined outside the class.
Write a program to find area of rectangle using scope resolution operator.
#include<iostream.h>
#include<conio.h>
class rectangle
{
int L,B;
public:
void get_data();
void area();
};
void rectangle::get_data()
{
cout<<"Enter Length of rectangle";
cin>>L;
cout<<"Enter breadth of rectangle";
cin>>B;
}
int rectangle::area()
{
return L*B;
}
int main()
{
rectangle r;
r.get_data();
cout<<"Area of rectangle is"<<r.area();
return 0;
}
Enter Breadth of rectangle 12
Area of rectangle is 144