const member functions

Hi guys :)

Can someone please explain the const modifier in the following line of code:

std::string isbn() const {return this->bookNo;}

I know that it has something to do with modifying the implicit this pointer, but I'm still not sure how it works. Thanks in advance!!

1
2
3
4
5
6
7
8
9
10
  struct Sales_data {
     // operations on Sales_data objects
     std::string isbn() const {return bookNo;}
     Sales_data& combine(const Sales_data&);
     // data members
     std::string bookNo;
     unsigned units_sold = 0;
     double revenue = 0.0;
};
     
Last edited on
const in this case simply means that the function is not allowed to change any class/struct-variables, unless they're marked mutable.
this is usually a const pointer as if:

Sales_data * const this;

In a const member function, this becomes a const pointer to const, as if:

const Sales_data * const this;

Essentially, this prevents the member function from modifying any of the member data in the Sales_data object.

http://ideone.com/71PNw4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Example
{
public:

	int i;

	void would_compile()
	{
		this->i = 1;
	}

	void wont_compile() const
	{
		this->i = 2;
	}
};

int main()
{
}
prog.cpp: In member function ‘void Example::wont_compile() const’:
prog.cpp:14:11: error: assignment of member ‘Example::i’ in read-only object
   this->i = 2;
           ^
Last edited on
Fantastic! Thank you both!!
Topic archived. No new replies allowed.