Passing value to const reference parameter?
Question
I haven't been able to find a similar question on here, or through Google, maybe because i don't know if I'm asking the right question, so not sure if the title is right. But I'm working with code that looks like this:
Foo * foo = new Foo();
add(*foo); //Couldnt find any similar questions on this syntax?
void add(const Foo & foo){
//What exactly is foo here? How can i manipulate its members, foo. or foo-> ?
}
Solution
The variable foo
inside the add
method is a constant reference. It behaves like a pointer in the sense that it does not copy the object: you interact with it as if it were the object itself. Unlike a pointer, a reference cannot be NULL
, and it cannot be reassigned. You interact with it using a dot .
operator instead of the ->
operator.
void add(const Foo & foo){
cout << foo.first_member << endl;
foo.const_member_function();
}
Since foo
is a constant reference, you can read foo
's members, but you cannot assign them. Also, any calls of member functions on the foo
reference are limited to functions explicitly marked const
.
Calling add
with a dereferenced foo
is OK, as long as foo
is not NULL
. Making a reference by dereferencing a NULL
pointer is undefined behavior.
OTHER TIPS
'foo' is a constant reference. You can access its members via foo.fred, foo.method(), etc., but you can't change any data members or call any non-const methods.