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?
Yes. Remember two things-
Reasons:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With