what is mean by const after the parameter?

Dec 11, 2015 at 10:56am
int getAge()const{return Age;}
Dec 11, 2015 at 11:00am
It is a promise that this class function will not change any class member variables, EXCEPT for any class member variables that are marked with the qualifier mutable in the class definition.
Dec 11, 2015 at 11:05am
i dont get what u mean by
Dec 11, 2015 at 12:15pm
const is useful because it prevents you from modifying things that are not supposed to be modified by mistake.

When you call getAge() you can be sure that it will not modify the object. If you tried to modify the Age (assuming it's a member variable) inside the function it would give you an error.

1
2
3
4
5
int getAge() const
{
	Age = 8; // error
	return Age;
}
Last edited on Dec 11, 2015 at 12:15pm
Dec 11, 2015 at 12:26pm
closed account (48T7M4Gy)
https://msdn.microsoft.com/en-us/library/07x6b05d.aspx

1
2
3
4
int getAge()const
{
   return Age;
} 


As an example getAge() could be a method/ member function related to an object which is an instance of a Person class.

const guarantees that getAge() is read only. i.e. it can only return the Person object's age and cannot alter any of the Person object's attributes/properties.
Topic archived. No new replies allowed.