Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"You can't forward declare classes that overload operator&"?

Tags:

c++

gcc

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?

like image 765
Head Geek Avatar asked Oct 06 '08 23:10

Head Geek


People also ask

What is forward declaration of a class when and why is it needed?

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.

What is forward declaration of a function?

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.

What is forward declaration in Cpp?

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.

Can we overload address of operator?

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.


2 Answers

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.

like image 131
fizzer Avatar answered Oct 01 '22 02:10

fizzer


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.

like image 37
Pete Kirkham Avatar answered Oct 01 '22 02:10

Pete Kirkham