Are there any situations to explicitly use the scope resolution operator with global scope? I can imagine a situation like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//Please ignore the nonsense from a design point of view
#include <cmath>
class IntWrapper{
public:
IntWrapper& pow(char);
IntWrapper(char);
private:
int m_int;
};
//...
IntWrapper::IntWrapper(char toconvert):
m_int(IntWrapper::pow(toconvert))
{
m_int = ::pow(m_int,100);
}
//Implementation of IntWrapper::pow(char)...
But then I would think that the writer should have used a different name, and that using the scope resolution operator in the constructor body is still pointless...
What do you mean by operator::? The way you write it, it sounds like you are going to overload it (which you can't AFAIK).
You can override the ::operatornew() or call it directly. It can be used just like malloc() (and frequently is coded to call malloc()). However, calling ::operatornew() allows for it to be overridden unlike malloc(). Default operatornew() for classes call ::operatornew().
there is an ambiguity because function pow is overloaded for floating numbers.
The correct code (without testing :) ) will be
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//Please ignore the nonsense from a design point of view
#include <cmath>
class IntWrapper{
public:
IntWrapper& pow(char);
IntWrapper(char);
private:
int m_int;
};
//...
IntWrapper::IntWrapper(char toconvert):
m_int(pow(toconvert))
{
m_int = ::pow((double )m_int,100.0);
}
//Implementation of IntWrapper::pow(char)...
By the way, std::pow is overloaded for integers (as of C++11, earlier in some compilers), only ::pow isn't.. which is another difference.
can you give an example on using ::operator new() ?
Effective C++ has a classic example:
1 2 3 4 5 6 7 8
void * Base::operatornew(size_t size)
{
if (size != sizeof(Base)) // if size is "wrong,"
return ::operatornew(size); // have standard operator
// new handle the request
... // otherwise handle
// the request here
}
It's in Item 8.
an example where ::foo() is necessary?
Every once in a while when I feel lazy, I write a container toupper as
1 2 3
#include <ctype.h> // not cctype!
...
std::transform(container.begin(), container.end(), container.begin(), ::toupper);
Ah, thanks for those examples. I tried figuring out an example from what AdrianH said, but everything I came up with seemed wrong or needlessly complex. Now that you posted that example with ::operator new(), I feel dumb for not having thought of that.
Just one last question: how common is ::foo in serious programs, including ::operator new()?