1

So I have a class called MusicComposer that has an AudioSignal object as a data member called music. Music is non-const. However, I need to return music as a const AudioSignal in a method called getMusic.

In the source file:

const AudioSignal& MusicComposer::getMusic(){

}

music is declared as:

AudioSignal music;

^ this is in the header file.

I declare music as non-const because music needs to be changed before it is returned by the getMusic method. However, I can't figure out for the life of me how to return a const version of it. How can I return a const version of music?

5
  • music will be changed to const when I return it? Commented May 16, 2014 at 23:39
  • Ahahah @Konrad Rudolph Commented May 16, 2014 at 23:39
  • No, the reference returned will be const. The object inside MusicComposer will still stay as is. Commented May 16, 2014 at 23:40
  • 1
    @user1799156 const is a property of the expression accessing the object, not the object itself. Commented May 16, 2014 at 23:40
  • 1
    @user1799156 Well, only when references are involved. An object (not reference) declared const will resist non-const access, and forcing the issue (with const_cast or similarly) produces undefined behavior (i.e., may crash). Commented May 16, 2014 at 23:56

2 Answers 2

2

C++ can automatically change mutable to const for you whenever. No biggie. It's going the other way that's hard.

return music;

If you really want to be explicit you could do this, but it's wierd code, and wierd is bad.

return static_cast<const AudioSignal&>(music);

Also, Cyber observed that getter methods themselves are usually const, which lets them be called even when MusicComposer is const.

const AudioSignal& MusicComposer::getMusic() const {
                                             ^^^^^
Sign up to request clarification or add additional context in comments.

Comments

1

Take a look in this example:

#include <iostream>

class A { // declare class A
  int integer;
};

class B { // declare class B
 public:
  const A& get() { // get() will return a const ref
    return a;      // here it is returning the ref of data member a
  }
 private:
  A a;
};

int main() {
  A a;
  B b;
  a = b.get();

  return 0;
}

As mentioned by potatoswatter,

const is a property of the expression accessing the object, not the object itself

Comments

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.