Sign in to follow this  
Cecil_PL

C++ function params: pointer-to-const vs. reference-to-const

Recommended Posts

I've got a quick (hopefully) question. :) Are there any semantic differences between the following code segments, and if so what would be the reasons to prefer one over the other?
void Foo(const Bar* bar);
void Foo(const Bar& bar);
Other than personal preference of using "->" or ".", are there any other reasons I should lean to using one or the other of these?

Share this post


Link to post
Share on other sites
If the parameter can refer to a null pointer then you should use a pointer, otherwise use a reference.

Share this post


Link to post
Share on other sites
I difference is:
const Bar* bar is a pointer to a const Bar
but you can do the following (eg. by mistake)

const Bar A,B;
const Bar* ptrA = &A;
ptrA = &B;

so you could chang what the pointer points to in the function scope. Which of course you can not with a reference.

So execpt for what rip-off said the following will behave the same:

const Bar* const bar
const Bar& bar


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this