C ++ problem with parameter to send

I am currently coding a project, and I have a function that looks like this:

Room::addItem(Item*&); //not written by me 

I have some problems understanding what to send as a parameter .. "* &" confuse this for me.

I tried the following:

 foo.addItem(loadItem()); //Returns an Item-object /*and*/ foo.addItem(loadItem()); //Returns an Item-pointer 

edit: It would be nice if you explained what "* &" is. means. I want to understand this the next time I do this;)

+4
source share
4 answers

The addItem function takes an argument of type Item* , and the pointer is passed by reference. This means that the addItem function can internally change the pointer. It may also mean that the object is being redistributed or changed inside this function.

Example:

 void pointerByValue(int* ptr) { ptr = new int[10]; } void pointerByReference(int*& ptr) { ptr = new int[10]; } void main() { int* p = NULL; //A NULL pointer pointerByValue(p); //p is still NULL pointerByReference(p); //memory has now been allocated to p } 

The pointer by reference is valid only in C ++.

+2
source

It seems to me that your function is expecting a pointer reference. For example, MSDN has some sample code with similar syntax.

 // Add2: Add a node to the binary tree. // Uses reference to pointer int Add2( BTree*& Root, char *szToAdd ) { if ( Root == 0 ) { ... 

There are various reasons why you might want to do this, but your favorite search engine should help you there. One blog entry to point you in the right direction, here .

+2
source

The type of the parameter is a reference to a pointer to an Item and what you need to pass is a pointer to an Item (i.e., Item* ), which should also be an lvalue (because presumably Room::addItem is going to change the pointer).

+1
source

you need to pass a pointer to a function

 Item item = loadItem() foo.addItem(&item); 

& means that the function will use the link and will be able to change its value

+1
source

Source: https://habr.com/ru/post/1447487/


All Articles