Compiler error about invalid initialization of a reference like something & from expression like something *

I have a prototype of a function like

test(something &)

      

and i do

something *ss = new something();

      

and I say

test(ss)

      

the compiler complains that initializing a reference like something & from an expression is something *.

but that doesn't mean the new one returns an address and ss must point to that address! so if the test expects a link then doesn't ss represent a link?

+3


source to share


3 answers


Your function expects a regular object something

. You don't need to use a pointer here:

something ss;

test(ss);

      



When your function signature looks like f(T&)

it means it accepts an object reference T

. When signed f(T*)

, it means that it accepts a pointer to an object T

.

+3


source


Your function expects a reference to something

, and you pass it a pointer to something

. You need to remove the link from the pointer:

test(*ss);

      



Thus, the function refers to the object it points to ss

. If you have an object something

, you can pass it directly:

something sss;
test(sss); // test takes a reference to the sss object.

      

+2


source


you are confused by reference and variable address.

If your function prototype is:

test(something &)

      

You can call it something object

:

something ss;
test(ss);

      

You can call it something pointer

:

 something *ss = new something();
 test(*ss);

      

If your function is:

test(something *)

      

You may call:

something *ss = new something();
test(ss);

      

0


source







All Articles