Any member function that doesnt change any member variables must be declared const to gurantee that its not going to change anything. Im not 100% positive but if you take it out you should get a compiler error.
That's incorrect. A member function doesn't have to be declared const. It only has to be declared const if you want to call it with const objects. Of course, a const function cannot contain code that changes the object.
Just remember any member function that doesnt change any member variables should be declared const.
Now you got it.
Would it be bad if I decided to delete that part of the code?
Yes. Why do you want to delete it?
The const at the end of a function means that the function is const. What does that mean? First, const after a function only has any relevance when you have a member function. You do not do this:
Code:
void greeting() const
{
cout<<"hello";
}
greeting() is not a member function.
The const after a member function, like you have, says that the member function will not change the object that is calling the function. Changing the calling object would entail doing something like this:
Code:
const string &Armor::getName()
{
name = "Betty";
return name;
}
That function changes the name member of the calling object. If a function is declared const, it cannot contain code that changes the calling object, and as a result the calling object can be an object that was declared const, e.g.:
const Armor myArmor;
Remember if an object is declared const, it is not allowed to be changed. If the member function did not have const after it, then an object that was declared const could not call the member function because a const object needs a guarantee that it won't be changed. A regular object has no such restriction, so a regular object can call a member function that does not have const after it. In that case, the member function can change the member variables of the object.
Since you want as many objects of your class as possible to be able to call the member functions, you should declare any function as const when it doesn't need to change the calling object.
Code:
#include <iostream>
using namespace std;
class Apple
{
private:
int size;
public:
Apple(int s=0)
{
size = s;
}
void display() //no const
{
cout<<"size is: "<<size<<endl;
}
void show() const //const
{
cout<<"size is: "<<size<<endl;
}
void print() const //const function that attempts to change calling object
{
//size = 10; //error
cout<<"size is: "<<size<<endl;
}
};
int main()
{
Apple apple1(5);
const Apple apple2(10);
apple1.display();
//apple2.display(); //error
apple1.show();
apple2.show();
return 0;
}