In the Google C++ Style Guide, there's a section on Operator Overloading that has a curious statement:
Overloading also has surprising ramifications. For instance, you can't forward declare classes that overload
operator&
.
This seems incorrect, and I haven't been able to find any code that causes GCC to have a problem with it. Does anyone know what that statement is referring to?
A forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types.
In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.
Forward declaration lets the code following the declaration know that there is are classes with the name Person. This satisfies the compiler when it sees these names used. Later the linker will find the definition of the classes.
Two operators = and & are already overloaded by default in C++. For example, to copy objects of the same class, we can directly use the = operator. We do not need to create an operator function. Operator overloading cannot change the precedence and associativity of operators.
5.3.1 of the Standard has "The address of an object of incomplete type can be taken, but if the complete type of that object is a class type that declares operator&() as a member function, then the behavior is undefined (and no diagnostic is required)."
I didn't know this either, but as another poster has pointed out, it's easy to see how it could cause a compiler to generate incorrect code.
I hadn't heard of it either, but this gives potentially confusing results for the same code before and after the overload:
#include <iostream>
class Foo;
void bar (Foo& foo) {
std::cout << &foo << std::endl;
}
class Foo {
public:
bool operator & () { return true; }
};
void baz (Foo& foo) {
std::cout << &foo << std::endl;
}
int main () {
Foo foo;
bar(foo);
baz(foo);
return 0;
}
output:
0x7fff092c55df
1
Though there are other reasons why you wouldn't do that anyway - overloading address-of doesn't play nicely with stl or much generic code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With