user1799156
user1799156

Reputation: 21

C++ how to return a const object from a class variable

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?

Upvotes: 1

Views: 86

Answers (2)

gsamaras
gsamaras

Reputation: 73366

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

Upvotes: 1

Mooing Duck
Mooing Duck

Reputation: 66922

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 {
                                             ^^^^^

Upvotes: 2

Related Questions