user3139868
user3139868

Reputation: 403

What does ampersand before closing bracket do in C++ function declaration?

Found this example and wonder what the & before the closing bracket does?

void f(const Foo &)
{
    std::cout << "f(const Foo&)\n";
}

Example taken from here

Help will be much appreciated.

Upvotes: 2

Views: 367

Answers (3)

Rahul Tripathi
Rahul Tripathi

Reputation: 172578

In simple terms the & says it's a reference.

So when you use the & operator in the function declaration, preceded by a type(here it is Foo) it means "reference to" which is essentially an automatically dereferenced pointer with disabled pointer arithmetic.

Also check this reference for details

Upvotes: 1

stefaanv
stefaanv

Reputation: 14392

In C++, if you don't use a parameter, you don't have to name it. Some compiler settings even generate warnings if you do name them. An unnamed parameter only consists of a type and the type can also be a pointer or a reference or combinations of them. In this case (as already answered), the type is a reference.

Unused parameters are mostly useless and should be avoided, but they can exist in virtual functions, where some implementations need them and others don't.

Upvotes: 2

Mercious
Mercious

Reputation: 398

Its a reference to type Foo. You should get yourself a C++ book and read through it.

http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29

Upvotes: 1

Related Questions