it might sound stupid.in C++prime 5th edition P258,it says:
by default, the type of this is a const pointer to the nonconst version of the class type.for example,by default, the type of this in a Sales_data member function is Sales_data *const.
i can understand that for this* is a const pointer which means the object it points once initialized cannot change.but then it says:
although this is implicit, it follows the normal initialization rules,which means that(by default)we cannot bind this to a const object.
but i wrote the following codes,it was still compiled fine:
class Test{
public:
Test() = default;
Test(const string &s): teststr(" ") {};
Test(int a) : testint(a) {};
Test(const string &s, int a): teststr(s), testint(a) {};
string getstr() const { return teststr; };
int getint() { return testint; }; //there is no const here
private:
string teststr;
int testint = 0;
};
int main(){
Test a("abc",2);
cout << a.getint() << " ";
cout << a.getstr() << endl;
cout << endl;
return 0;
}
so my question is : if the compiler can compile it fine whether there is a 'const' or not,why does it matter? and then the book says:
after all,the body of isbn doesn't change the object to which this points, so our function would be more flexible if this were a pointer to const.
and i'm wondering what is the flexiblity is?would you show me some examples?
For beginners, this
is often depicted as a constant pointer.
However, this
is actually a prvalue (pure rvalue) of pointer type. You can't assign anything to prvalues of fundamental type, which implies the "const-ness" of this
.
The exact type of this
depends on the cv-qualification of the method. A rule of thumb is that the cv-qualification is simply prepended to the usual pointer type - i.e., if a method of Class
is marked const
, then the type is const
Class*
.
if the compiler can compile it fine whether there is a 'const' or not,why does it matter?
If (and only if) the pointee type of this
is const
, you can't modify the members of the class.
Class const* ptr; // ptr->data is also const, not modifiable through this pointer
Class* ptr; // ptr->data isn't const - can be modified.
The const
-qualifier on methods allows you to distinguish between methods for const
objects and methods for non-const
ones, which is often a necessity.