operator ::

Is there any difference between these two?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int x=0;

class example
{
public:
void modify(int m)
  {
    x=m; // opeator :: not used here
  } 
};
int main()
{
example e;
e.modify(10);
}

and
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int x=0;
class example
{
public:
void modify(int m)
   {
      ::x=m; // :: !!!
   }
};
int main()
{
example e;
e.modify(10);

}

And why :: can be used here?
Thanks for help!
http://en.wikipedia.org/wiki/Operators_in_c_and_c%2B%2B#Other_operators

Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

namespace fooey
  {
    int x = 0;
  }

class example
  {
  public:
  void modify(int m)
    {
      ::x=m;  // won't compile.
    }
  };

int main()
  {
    using namespace fooey;
    example e;
    e.modify(10);
    cout << x << endl;
    return 0;
  }

Now change line 14 to read ::fooey::x=m; and recompile.

Enjoy!
So it tells in which scope look for a variable, right?
::x -- variable declared globally
::fooey::x --variable declared in fooey (fooey is declared in global scope)

there is no difference in this case. You use :: if you have a local variabel or a member variabel
with the same name as a global variabel. Then if you use :: before the name you will
use the global variabel. Here is an example with a local and global variabel:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int x = 10;

int main()
{
    int x = 20;
    cout << "Global variabel: " << ::x << endl;
    cout << "Local variabel: " << x << endl;
    return 0;
}


Output:

Global variabel: 10
Local variabel: 20


And then with a global and member variabel:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

int x = 10;

class TestClass
{
public:
   TestClass();
   void getX();
private:
   int x;
};

TestClass::TestClass()
{
  x = 20;
}

void TestClass::getX()
{
  cout << "Global variabel: " << ::x << endl;
  cout << "Local variabel: " << x << endl;
}

int main()
{
    TestClass testObject;
    testObject.getX();
    return 0;
}


Output:


Global variabel: 10
Local variabel: 20
Last edited on
Thanks.
Topic archived. No new replies allowed.