Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call non-const function on a const object

I am reading C++ Primer 5th edition page 258. The question is, can a const object call its non-const member function, even if that member function does not modify its data?

Sales_data.h

#include <iostream>
#include <string>

struct Sales_data {
    // data members
    std::string bookNo;
    unsigned units_sold = 0;
    double revenue = 0.0;

    // memeber functions
    const std::string isbn() const { return bookNo; }
    Sales_data& combine(const Sales_data&);
    double avg_price() const { // *
        if (units_sold) {
            return revenue / units_sold;
        }
        return 0.0;
    }
};

std::ostream& print(std::ostream &os, const Sales_data& data) {
    os << data.isbn() << " " << data.units_sold << " " << data.avg_price();
    return os;
}

use_Sales_data.cpp

#include <iostream>
#include "Sales_data.h"
using  namespace std;

int main(){
    Sales_data data;
    data.bookNo = "CSAPP";
    data.units_sold = 2;
    data.revenue = 50;
    print(cout, data);
}

When I remove the const for function avg_price, then the code does not compile. But I think the function avg_price() does not modify the object. My guessing is that, in the parameter list of print, I declared Sales_data object as const and C++ does not allow const object to call its nonconst member function. Is this the case?

like image 308
yyFred Avatar asked Mar 04 '23 17:03

yyFred


1 Answers

Yes. Remember two things-

  1. If the function is non-constant, it can only be called by a non-constant object.
  2. If the function is constant, it can be called on any objects (I mean any constant or non-constant objects.)

Reasons:

  1. If the function is non-constant, then the function is allowed to change values of the object on which it is being called. So the compiler doesn't allow to create this chance and prevent you to call a non-constant function on a constant object, as constant object means you cannot change anything of it anymore. So the compiler only allows you to call it on a non-constant object as this object can be modified.
  2. If the function is constant itself, then it is promising that it won't change anything of the object on which it is being called. So the compiler doesn't care whether you are calling a constant function on a constant or non-constant object as the function itself is unable to change the object.
like image 143
hafiz031 Avatar answered Mar 15 '23 01:03

hafiz031