1

Consider the following code:

class A{

  my_method(const B& b){
    import_something_from_c(this, b.getC()); // does some sort of copying
  }

}

class B{
  const C& getC() const { return c; };
}

function f(B b){
  b.getC().changeSomething();
}

Since my_method guarantees const, b.getC() must also be const. In f however, I do not guarantee constness and I do want to change the very same b.getC().

Is there some sort of a way to propagate the constness of an object to methods returning references to its members?

1 Answer 1

3

You need to provide a non-const overload of getC(). For example

C& getC() { return c; };
Sign up to request clarification or add additional context in comments.

4 Comments

Is it that simple? I always thought I could not overload return values. Constness of the value therefore is an exception?
@Michael This isn't overloading return value, it is overloading on the constness of the member function.
You are changing more than just the return value since you are also removing the second occurrence of the keyword const. That second const is actually part of the method signature.
Note, if the methods are complicated then to avoid code duplication you can have the non-const one call the const one, e.g.: C &getC() { return const_cast<C &>( const_cast<C const &>(*this).getC() ); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.