Thursday, 18 June 2015

Global scope resolution

Global scope resolution in Cpp with example.

This post will give the clarification about the Global scope of the variables.
The scope resolution operator gets you out of situations in which the name the compiler chooses by default is not what you want.

For example, suppose you have a structure with a local identifier iVal, and you want to select a global identifier iVal from inside a member function. As usual, the compiler would default to choosing the local one. Otherwise, we so must tell it to consider the global variable.

When you want to specify a global name using scope resolution, you use the operator with nothing in front of it.

Here is an example that shows global scope resolution for both a variable and a function:

#include "stdafx.h"

#include <fstream>

#include <iostream>

#include <string>

using namespace std;

int iVal;

void GolbalFun()


struct MyStruct


int iVal;

void GolbalFun ();


void MyStruct::GolbalFun ()


::GolbalFun (); // Would be recursive otherwise!

::iVal++; // Select the global iVal

iVal--; // The iVal at struct scope


int _tmain (int argc, _TCHAR* argv[])


  MyStruct s; GolbalFun ();

  getchar ();

  return 0;


Without scope resolution in MyStruct::GolbalFun (), the compiler would default to
selecting the member versions of GolbalFun ( ) and iVal.

No comments: