AnKo
AnKo

Reputation: 33

Parameter both a pointer and reference?

I'm checking out an assignment, and I've just found this in a header file, which I have to fill up in a .cpp:

void setData(const component_t * & data_ptr); // Copy the data from data_ptr to the internal buffer. 
//The function ASSUMES a proper size for the incomming data array.

If you're wondering about component_t, it's a float through typedef.

So, my question is, what kind of parameter is data_ptr? How can it be defined both by * and & (both a pointer and reference?).

Thanks for your insights!

Upvotes: 1

Views: 131

Answers (1)

Tristan Brindle
Tristan Brindle

Reputation: 16824

The parameter data_ptr is a reference to a pointer to a const component_t.

In C and C++, a pointer isn't really special. It's just a number that points to an address in memory. Usually when you pass a T* as a parameter, you are passing by value; that is, the number representing the memory address is just copied, the same as if you passed an int by value.

In this case, you are passing a T*&, or reference-to-pointer-to-T. But it works in much the same way as if you passed an int&, or reference to int: it means that you're allowed to change the referenced object.

So in this case you could say, for example

void setData(const component_t * & data_ptr)
{
    data_ptr = new component_t(/* args... */);
}

although this is not necessarily a good way to do things in modern C++.

Upvotes: 4

Related Questions