OOPortal 





Building C++ Classes  «Prev  Next»
Lesson 3 The scope resolution operator
ObjectiveUnary form of the scope resolution operator.
The scope resolution operator's unary form is used to access a variable or object that is at external scope and that has been "hidden" by an identically named variable or object declared at local or class scope.
int count = 0;        //external variable
 void how_many(double w[], double x, int& count)
{
    for (int i = 0; i < N; ++i)
      count += (w[i] == x);
    	++ ::count;         //keep track of calls
}
Example of unary scope resolution operator
#include <iostream>
using namespace std;

int n = 5; 

int main()
{
   double n = 11.7;

   cout << "Local double value of n = " << n
      << "\nGlobal int value of n = " << ::n << endl;
   return 0;
}
Local double value of n = 11.7
Global int value of n = 5


Defining Methods

The preceding definition for the SpreadsheetCell class is enough for you to create objects of the class.
However, if you try to call the setValue() or getValue() methods, your linker will complain that those methods are not defined. That is because the class definition specifies the prototypes for the methods, but does not define their implementations. Just as you write both a prototype and a definition for a stand-alone function, you must write a prototype and a definition for a method. Note that the class definition must precede the method definitions. Usually the class definition goes in a header file, and the method definitions go in a source file that includes that header. Here are the definitions for the two methods of the SpreadsheetCell class:
#include "SpreadsheetCell.h"
void SpreadsheetCell::setValue(double inValue){
mValue = inValue;
}
double SpreadsheetCell::getValue() const
{
return mValue;
}
Note that the name of the class followed by two colons precedes each method name:
void SpreadsheetCell::setValue(double inValue)
The :: is called the scope resolution operator. In this context, the syntax tells the compiler that the coming definition of the setValue() method is part of the SpreadsheetCell class. Note also that you do not repeat the access specification when you define the method.