Search code examples
c++referenceconstantsqualifiers

Why does 'const' behave differently in these two cases?


I have a question about just why a certain thing can be compiled when done "in one step" but can't when done "in two steps". I have three classes;

class Time {
  int mTime;

  int Time::getTimeAsUnix() const {return mTime;}
}

class Travel {
  Time mTimestamp;

  const Time& Travel::getTime() const { return mTimestamp; }
  Time& Travel::getTime() { return mTimestamp; }
}

class Analysis : public Travel {

  int Analysis::getUnixTime() const {
    // Time& t = Travel::getTime();
    // return t.getTimeAsUnix();     // This does NOT compile

    return Travel::getTime().getTimeAsUnix();  // This compiles
  }
}

Anyone knows why, in the Analysis class, the non-commented approach compiles while the commented approach gives me an instant "c++ error: binding 'const Time' to reference of type 'Time&' discards qualifiers" when I try?

Aren't the two the exact same thing when executed??


Solution

  • The line

    Time& t = Travel::getTime();
    

    needs to be

    const Time& t = Travel::getTime();
    

    for it to work. The reason this is needed is because you are inside a const-qualified function. When you are in a const-qualified function all members of the class are considered to be const. That means when you call getTime you call the

    const Time& Travel::getTime() const { return mTimestamp; }
    

    version of the function. Trying to assign a const Time& to a Time& wont work because you would be stripping away the constness of the return type.