I have a function prototype like
test(something &)
and i am doing
something *ss = new something();
and i say
test(ss)
compiler complains saying initialization of reference of type something& from expression something * .
but isn't that new returns the address and ss must point to that address ! so if test is expecting a reference is not it ss represents a reference ?
Your function expects a normal something
object. You don't need to use a pointer here:
something ss;
test(ss);
When your function signature looks like f(T&)
, it means that it accepts a reference to a T
object. When the signature is f(T*)
, it means that it accepts a pointer to a T
object.
Your function expects a reference to something
, and you are passing it a pointer to something
. You need to de-reference the pointer:
test(*ss);
That way the function takes a reference to the object pointed at by ss
. If you had a something
object, you could pass that directly to:
something sss;
test(sss); // test takes a reference to the sss object.
you are confused by reference and address of variable.
If your function prototype is:
test(something &)
You could call it with something object
:
something ss;
test(ss);
You could call it with something pointer
:
something *ss = new something();
test(*ss);
If your function is:
test(something *)
You could call:
something *ss = new something();
test(ss);