Reputation: 763
I was reading the book C++ Primer by Stanley B. Lippman and in the section of Variables and Basic Types I saw the scope operator ::
.
I had already read a little about the operator overload and I think it could be very useful in special cases, but when I searched in the internet I found out that I simply cannot overload the ::
operator.
In this post I found that the .
operator can be overload. However, this can lead to questions about whether an operation is meant for the object overloading .
or an object referred to by .
.
Thus, I think that maybe there is a way to overload the ::
.
But if it can't, can anyone explain me why?
An example of my idea for the :: operator:
#include <iostream>
/*
*For example:
*I wanna increase 1 unit every time
*I call the global variable r doing ::r
*insede of the main function
*/
int r = 42;
int main()
{
int r = 0;
std::cout << ::r << " " << r << std::endl; //It would print 43 0 after the operator overload
return 0;
}
Upvotes: 3
Views: 639
Reputation: 15916
You cannot overload it.
The scope "operator" unlike all the operators does nothing at run time, it affects the name lookup at compile time and you cannot change it since its job it is only to tell the compiler where to find names.
That's why you can't overload it.
For example:
#include <iostream>
#include <string>
std::string s = "Blah";
int main()
{
std::string s = "World";
::s = "Hello ";
std::cout << ::s << s << std::endl;
return 0;
}
Upvotes: 9
Reputation: 180945
The reason you cannot overload ::
is the standard forbids it. Section 13.5.3 has
The following operators cannot be overloaded:
.
.*
::
?:
Upvotes: 8