Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ const member function returning reference to class member

If I have the class member function:

bar* foo::get_value() const
{
  return &_value;
}

the compiler will complain

cannot initialize a variable of type bar * with an rvalue of type const bar *

_value is not const in the class.

If I have the function:

bar* foo::get_value() const
{
  return const_cast<bar *>(&_value);
}

It works just fine.

I thought that declaring a member function constant meant that you promise to not modify the internal contents of the class, but the operation & seems to return a constant pointer in const member functions. Why is this?

like image 445
mikesol Avatar asked Aug 28 '26 00:08

mikesol


1 Answers

When you declare a function const, you are saying that this is a function that is permitted on both a non-const and const instance of the object. Because it can be invoked on a const instance, the function should not mutate the object. When you return a non-const reference to an internal object, you are providing the caller with a way of mutating the object's internal state indirectly. To fix this, return a constant object, instead.

In other words, instead of:

Bar* Foo::GetBar() const

Do:

const Bar* Foo::GetBar() const

Or, better yet:

const Bar& Foo::GetBar() const

As you've observed, const_cast allows you to undermine the const-ness of the object. In general, you should avoid using const_cast; using it is a code smell, and it undermines the intended const gurantees.

like image 99
Michael Aaron Safyan Avatar answered Aug 30 '26 14:08

Michael Aaron Safyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!