Make all the
appropriate function constant. Include a constant data member called id of integer
type.
Create two object constant and non-constant. Assign values and display them. Also
check what happens
If you try to modify private data member of an object from the definition of
const function
If you try to modify the private data member of const object from the
definition of non-constant function.
#include <iostream>
using namespace std;
class Constant {
int id;
public:
int value;
Constant(int v = 0) { id = v; }
int getvalue() {return value;
}
int getid() const { return id; }
};
int main()
{
Constant t(10);
cout<<t.getid();
return 0;
}
Any attempt to modify the private member variables of the object is disallowed as it will violate the constant-ness of the object.
compilation error will occur if you also try to modify private data member of constant object from definition of non-constant object. This is because every class method is a function that implicitly passes this as a parameter. When you declare a method as constant, that means that it will actually pass constant this to this function therefore it is both correct logically and syntactically not to call not constant methods from constant methods.
Comments
Leave a comment