On const reference arguments passing

G

Giff

Hi,

I am trying to change my way of programming (I am still learning) , in
particular I am putting an effort in passing const ref to functions,
when possible.

When possible means (to me) when that function is not going to modify
the object I pass to it.

Many times though, I create an object, call a function (taking a non-
const ref) that modifies it somehow and then
need to use that object as parameter for a function that takes a const
ref, that will only read the object.

The compiler complains, since I am passing a non-const object to the
function and the only thing that I can do is to cast away the
constness, but is this the right way to go? It feels wrong...

Thanks for your hints.

/G
 
V

Victor Bazarov

Giff said:
I am trying to change my way of programming (I am still learning) , in
particular I am putting an effort in passing const ref to functions,
when possible.

When possible means (to me) when that function is not going to modify
the object I pass to it.

That's a good rule. Also, when you think of treading the object as
"a value", it may still be reasonable to pass by reference to const,
instead of passing by value.
Many times though, I create an object, call a function (taking a non-
const ref) that modifies it somehow and then
need to use that object as parameter for a function that takes a const
ref, that will only read the object.

That sounds reasonable.
The compiler complains, since I am passing a non-const object to the
function and the only thing that I can do is to cast away the
constness, but is this the right way to go? It feels wrong...

That doesn't sound right. Could you please support this statement
with code? I can only see such behaviour of the compiler if the
situation is reversed -- calling a function expecting a ref to non-
const object from a function where the object is const (i.e. you
passed the object by reference to const):

class a {};
void foo(a& ra);
void bar(a const & ra) {
foo(ra); // error
}
int main() {
a object;
bar(object);
}

V
 
G

Giff

That doesn't sound right.

I know, sorry for the post. I was doing something else wrong and I
have just been too impatient.
My apologies to the group, and thanks for your reply anyway.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,836
Latest member
login dogas

Latest Threads

Top