TAGS :Viewed: 2 - Published at: a few seconds ago

[ Method signature C++ ]

Having trouble understanding method signature in C++. Looking for a second opinion.

readPage(File* file, const PageId pageNo, Page*& page) {}

The above can be re-written as follows?

readPage(File *file, const PageId pageNo, Page *&page) {}

So, *file is pointer that is being passed in and *&page is something's address that is then converted to a pointer? I'm confused with the combination of *&

Answer 1

file is a pointer to a File, which means that any changes to what it points to, like

file->doSomething(); // the caller will see this change

will be seen by the calling side, but if one overwrites the pointer, that not only the new value of the pointer not going to be seen by the caller, but any changes to the file after that will also not be observed, because it's a pointer to a different File now, and because the pointer itself is passed by value.

file = new File(); // the caller will not see this change
file->doSomething(); // neither will it see this one

Now, page is a reference to a pointer to a Page. In other words, it behaves like a pointer, so

page->doSomething(); // the caller will see this change

is still observed by the caller. But now if you overwrite the pointer, the caller's pointer will also be changed, and hence all consecutive changes will also be seen:

page = new Page(); // caller also sees this change
page->doSomething(); // and this too

This is because the pointer itself is passed by reference, so any changes to the pointer itself are observed by the calling side.

(and yes, the way you place spaces does not matter, so the two ways you provided are identical)

Answer 2

Page*& is reference to pointer to a Page