top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is a scope resolution operator in C++?

+1 vote
424 views
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

Definition:

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:

#include 
#include 
static std::string myPath;

__attribute__((constructor))
void SetPath() {
 Dl_info dl_info;
 dladdr((void*)SetPath, 
 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?

...