top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

What is a scope resolution operator in C++?

+1 vote
What is a scope resolution operator in C++?
posted Jan 12, 2015 by Emran

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
Best answer


Use the double colon operator (::) to qualify a C++ member function, a top level function, or a variable with global scope with: An overloaded name (same name used with different argument types) An ambiguous name (same name used in different classes)

class A 
  static int i;  // scope of A

namespace B
  int j;
int A::i = 4; // scope operator refers to the integer i declared in the class A
int B::j = 2; // scope operator refers to the integer j declared in the namespace B

The :: (scope resolution) operator is used to qualify hidden names so that you can still use them. You can use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in a block or class. For example:

int count = 0;

int main(void) {
  int count = 0;
  ::count = 1;  // set global count to 1
  count = 2;    // set local count to 2
  return 0;
answer Jan 29, 2015 by Mohammed Hussain
+2 votes

Scope resolution operator(::) is used to define a function outside a class or when we want to use a global variable but also has a local variable with same name.

#include <iostream>
using namespace std;

char c = 'a';     // global variable

int main() {
  char c = 'b';   //local variable

  cout << "Local c: " << c << "\n";      
  cout << "Global c: " << ::c << "\n";  //using scope resolution operator

  return 0;
answer Jan 12, 2015 by Gnanendra Reddy
Similar Questions
+1 vote

I have a need for certain functions in a shared library to know the path to that library in order to find various resources. What I have in source.cpp:

static std::string myPath;

void SetPath() {
 Dl_info dl_info;
 myPath = dl_info.dli_fname; // 

As the comment shows, when built with optimizations enabled, that line produces a segfault. With no optimizations, it works just fine. What magic must be done in order to ensure that this variable exists before the "constructor" function is called when loading the shared library?

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.