0

I have a class which gives value for a corresponding time. I have a method that changes the m_time (in hh,mm,ss)[ms] but is declared as const at the end. So I need to change the attribute m_time but I can't ! how could I possibly go around this?

Here is my code:

class CMeasurementValue
{
private:
    double m_value;
    unsigned int m_time;

public:
    CMeasurementValue(double value=0,unsigned int time=0);
    CMeasurementValue(double value,unsigned int hh,unsigned int mm , double ss);
    double getValue() const ;
    unsigned int getTime() const;
    void calculateTime(unsigned int& hh , unsigned int& mm , double& ss ) const;
    bool operator <(const CMeasurementValue& rop)const ;
    friend ostream& operator <<( ostream& out, const CMeasurementValue& rop);
    void print();
};

void CMeasurementValue::calculateTime(unsigned int& hh , unsigned int& mm , double& ss) const
{
    // ??
}
NutCracker
  • 11,485
  • 4
  • 44
  • 68
  • 7
    You cannot change class members without either removing `const` from method or making that member `mutable`. But are you sure you should edit any member? My intuition suggests that method `calculateTime` should take whatever is currently stored in the class and based on that calculate `hh`, `mm` and `ss` (and return those value to caller via output parameters). You should probably ask whoever gave you constraints what they meant. – Yksisarvinen Feb 06 '20 at 22:33

1 Answers1

0

You can declare your member m_time mutable like this:

class CMeasurementValue {
private:
    double m_value;
    mutable unsigned int m_time;
    // ...
};

From the docs:

  • mutable - permits modification of the class member declared mutable even if the containing object is declared const.

However, if the function calculateTime, which is marked as const, is supposed to change the state of one of the members, why is it then marked as const?

NutCracker
  • 11,485
  • 4
  • 44
  • 68
  • it was a header from an exam , it was declared like that . i think it's more like a security or something like that . the question is if i change the declaration to mutable what's effect has that on the attribut ? – Ahmed Ladhibi Feb 07 '20 at 06:26
  • like you said guys i missunterstood the purpose of the methode , the purpose is to calculate the m_time [ms] iin hh,mm,ss ! so the purpose is not to change the attribut m_time but to extract the information (hh,mm,ss ) from it , that's explain also why the parameter is as Ref& declared ! thank you very much guys , i learned at least what mutable make – Ahmed Ladhibi Feb 07 '20 at 08:44
  • @AhmedLadhibi no problem really, I am glad I helped you – NutCracker Feb 07 '20 at 08:45