In: Computer Science
Research "Const Correctness" and answer the following questions:
Given:
class SimpleClass { private: int _x; public: SimpleClass(int x) : _x(x){} int getX() const { return _x; } void setX(int newX) { _x = newX; } void displayDataWithCustomMessage(const string &customMessage) { cout<<"Data: "<<_x<<endl; cout<<"Custom Message: "<<customMessage<<endl; } };
1. What is the usefulness of the "const" keyword in the definition of the "getX" member function?
The const keyword is used in the definition of getX() member function to allow it to be called by const or non const object from main method. If const keyword is not used , we cannot call this function getX() from const object.
2. What is the usefulness of the "const" keyword in the definition of the "displayDataWithCustomMessage" member function?
const SimpleClass t(10); // const object
cout<<t.getX();
t.displayDataWithCustomeMessage(" is verified"); //
will generate compilation error.
3. Why shouldn't the "const" keyword be used in the definition of the "setX" member function?
Set methods are used to change the values of variables . But const methods do not allow to change the variable values. So const keyword should not be used with setX();
#include <iostream>
using namespace std;
class SimpleClass
{
private:
int _x;
public:
SimpleClass(int x) : _x(x){}
int getX() const // if we don't use const method , const objects
cannnot call this function
{
return _x;
}
void setX(int newX)
{
_x = newX;
}
void displayDataWithCustomMessage(const string
&customMessage)
{
cout<<"Data: "<<_x<<endl;
cout<<"Custom Message:
"<<customMessage<<endl;
}
};
int main() {
// both const and non const objects can call const
functions
const SimpleClass t(10); // const object
cout<<t.getX();
t.displayDataWithCustomeMessage(" is verified"); //
will generate compilation error.
SimpleClass t1(10); // non const object
cout<<t1.getX();
t1.displayDataWithCustomeMessage(" is
verified");
return 0;
}
Do ask if any doubt. Please upvote.