Search code examples
c++constantspass-by-reference

passing reference to constant object while the object is not updated


I wrote a toy class below.

header

class saleData{
  private:
    std::string isbn;
    unsigned cnt;
    double price;

  public:
    saleData(const std::string s, unsigned c, double p): isbn{s}, cnt{c}, price{p} {};
    
    unsigned getCnt(){
      return cnt;
    }

    double getPrice(){
      return price;
    }

    saleData &combine(####const#### saleData &x){
      cnt += x.getCnt();
      price=(price*cnt + x.getCnt()*x.getPrice()) / (cnt + x.getCnt());
      return *this;
    }
};

main function

int main(){
  saleData x("xx", 3, 4.4);
  saleData y("yy", 4, 3.3);
  x.combine(y);
  cout<<"total revenue is "<<x.getCnt() * x.getPrice()<<endl;
  return 0;
}

If i have that ####const#### in the combine function, I would get some compile error like

sale_data.h:25:35: error: passing 'const saleData' as 'this' argument of 'unsigned int 
saleData::getCnt()' discards qualifiers [-fpermissive] 
       price=(price*cnt + x.getCnt()*x.getPrice()) / (cnt + x.getCnt());

If i remove the const, everything is working fine.

But i didn't modify anything for the saleData x right? I am just reading its cnt and price.


Solution

  • Non-const member functions (getPrice() and getCnt()) can't be called on const object. You should make them const, to tell that they won't modify any non-static data members.

    class saleData{
      private:
        std::string isbn;
        unsigned cnt;
        double price;
    
      public:
        saleData(const std::string s, unsigned c, double p): isbn{s}, cnt{c}, price{p} {};
        
        unsigned getCnt() const {
          return cnt;
        }
    
        double getPrice() const {
          return price;
        }
    
        saleData &combine(const saleData &x){
          cnt += x.getCnt();
          price=(price*cnt + x.getCnt()*x.getPrice()) / (cnt + x.getCnt());
          return *this;
        }
    };