Scope Resolution in C++.


The :: operator is used in two contexts.

  1. Global Variable Identification.
  2. Method Identification.

Global Variable Resolution

The :: operator is used within C++ to identify global variables that conflict with local variable names. Obviously it would be good programming practice to use suitable names in the first place......

    #include <iostream.h>

    int Counter = 1;

    main()
    {
        int Counter = 1;
   
        for (int i=0; i< 10; i++)
        {
            cout << " Local Counter = " << Counter
                 << " Global Counter = " << ::Counter
                 << endl;
   
            // Increment the local Counter.
   
            Counter++;
        }

        exit(0);
    }


Scope of Methods

Methods can be defined in one of two locations. Either within the class definition or outside the class definition. When the method definition is outside the class, it needs to identify its self with the class through the :: operator.

    #include <iostream.h>

    // Define the Animal class

    class Animal
    {
     public:

        int  GetNumOfLegs(void); // Declare a couple of methods
        void SetNumOfLegs(int L);

    private:
        int Legs;
    };

    // Define the methods. The :: operator associates the method with
    // the correct class.

    int Animal::GetNumOfLegs(void)
    {
        return Legs;
    }

    void Animal::SetNumOfLegs(int L)
    {
        Legs = L;
    }

    //*******************************************************

    main()
    {
        Animal Goat; 			// Create the goat object

        Goat.SetNumOfLegs(4); 		// Initialise the Goat object with some legs

					// Inform the user how many legs a goat has.
        cout << "Goats have "
             << (int) Goat.GetNumOfLegs()
             << " legs"
             << endl;

        exit(0);
    }
Method Scope


Examples:

oGlobal Variable Example Program.

oMethod Scope Example Program.


See Also:

oC++ operators..

C References

oGlobal Variables.

oC Expressions and Operators.


Top Master Index Keywords Functions


Martin Leslie