Return ref to a constant object

Write your question here.
Using eclipse, if the object is a constant, it allows to return a constant object too. The compiler complains "invalid initialization of reference of type 'Vector&' from expression of type 'const Vector'.


But, according to book C++ Primer plus Stephen Prata page 662, it should work.

Why is that? is there any setting i need to ignore this error?

thanks



// version 1
Vector Max(const Vector & v1, const Vector & v2)
{
if (v1.magval() > v2.magval())
return v1;
else
return v2;
}
In the code you posted, you aren't returning a reference, nor is the return value a constant. Did you make an error copying and pasting or something?
hi Firedraco,
Thanks a lot i understand now. I made a mistake by returning a reference.

int & f1(const int & piRef) {
return piRef;
}
Well, the problem there is that you are returning a non-const reference (which allows modification) to a const object (which doesn't), which you simply can't do because it violates const correctness.

If the book you are reading says you can, it is incorrect.
Topic archived. No new replies allowed.