Skip to main content

1. Write a cpp program which explains the use of a scope resolution operator.

The scope resolution operator (::) is used in C++ to specify the scope of a name. It can be used to access a global variable, function, or class from within a local scope.

Here's an example of how you can use the scope resolution operator to access a global variable from within a function:

#include <iostream>

using namespace std;

int x = 10; // global variable

int main()
{
int x = 20; // local variable
// access the global variable x
cout << ::x << endl; // prints 10

return 0;
}

Output

10

In this example, the global variable x is shadowed by the local variable x within the main function. To access the global variable x, we use the scope resolution operator (::) before the variable name.

Here's an example of how you can use the scope resolution operator to access a static member variable of a class:

#include <iostream>

using namespace std;

class A
{
public:
static int x;
};

int A::x = 10; // define static member variable

int main()
{
A::x = 20; // access static member variable

cout << A::x << endl; // prints 20

return 0;
}

Output

20

In this example, we use the scope resolution operator (::) to access the static member variable x of the class A.

We can use the operator to both define and access the static member variable.