OOPortal
J2EEOnline RationalDB
prev next prev next
Course navigation
Lesson 2 Scope resolution operator
Objective Unary, binary forms of the scope resolution operator
The scope resolution operator in C++ This page describes the unary and binary forms of the scope resolution operator in C++
The class construct adds a new set of scope rules to those you are already familiar with in C++. One point of classes is to provide an encapsulation technique. Conceptually, it makes sense that all names declared within a class be treated as if they were in their own namespace, distinct from external names, function names, and other class names. This creates a need for the scope resolution operator (::). The scope resolution operator is the highest precedence operator in the C++ language. It comes in two forms: unary and binary. We will examine these forms in the next two lessons.
The scope resolution operator helps to identify and specify the context to which an identifier refers.
The scope resolution operator (::) in C++ is used to define the already declared member functions (in the header file with the .h extension) of a particular class. In the .cpp file one can define the usual global functions or the member functions of the class.
To distinguish between the normal functions and the member functions of the class, one needs to use the scope resolution operator (::) in between the class name and the member function name
 i.e. Account::getBalance()
where Account is a class and getBalance() is a member function of the class Account.
The other uses of the resolution operator is to resolve the scope of a variable when the same identifier is used to represent a
  1. global variable,
  2. a local variable, and
  3. members of one or more class(es).
If the resolution operator is placed between the class name and the data member belonging to the class then the data name belonging to the particular class is referenced.
If the resolution operator is placed in front of the variable name then the global variable is referenced. When no resolution operator is placed then the local variable is referenced.
#include <iostream>
using namespace std;
int n = 12;   // A global variable

int main() {
   int n = 13;   // A local variable
   cout  << ::n << endl;  // Print the global variable: 12
   cout  << n   << endl;  // Print the local variable: 13
}
Course navigation