Why does the address operator come as a default member of C++ class and what is it?

790 Views Asked by At

There are 5 default members in C++ classes. Default constructor, destructor, copy constructor, assignment operator and address operator.

  1. What is an address operator? Is it className* operator &() {}?

  2. If so, why does the compiler generate this address operator by default (as we already have an address operator in C and we can get the address of an object without this extra overhead)? Is there any special purpose?

2

There are 2 best solutions below

3
On

You are starting from the wrong premise. The special member functions are (§12 [special]/p1)

  • the default constructor - implicitly declared if there is no user-declared constructor
  • the copy constructor and copy assignment operator - implicitly declared if not user-declared
  • the move constructor and move assignment operator - implicitly declared only if no copy/move ctor/assignment operator or destructor is user-declared
  • the destructor - implicitly declared if not user-declared

The unary operator & is not a special member function, and there is no such thing as a compiler generated operator &() function. If you write

struct B {} b;
B *pb = &b;

then what is used is the built-in & operator. No function call or overhead involved. It behaves just like if you took the address of a int variable.

There are programmers who manually overload unary operator &. This is usually a spectacularly bad idea.

0
On

In the section 13.3.1.2 of the C++ Standard concerning operator overload resolution one finds the following rule:

If the operator is the operator ,, the unary operator &, or the operator ->, and there are no viable functions, then the operator is assumed to be the built-in operator and interpreted according to Clause 5.

If all types were provided with a member operator& by default, the viable set could never be empty. Since there's a rule for what to do when the viable set is empty, you can therefore be sure that types initially don't have a member operator&.