I'm kind of confused with "consts" in this example. How can I change *this in the method (for example operator++) when there is "const" placed after method declaration -
const Complex Complex::operator++() const
I can do whatever I want to, just put *real = 123 - and it works....
But how???, when there is a const after method declaration.
a const method doesn't allow you to modify the value of the members, but *real = *(real) + 1; does not modify real, it modifies the object real is pointing to.
eg:
1 2 3 4 5 6 7 8 9 10 11
struct S
{
int a, *p;
void f() const
{
a = 0; // Error: modifies 'a'
p = &a; // Error: modifies the value of 'p'
*p = 0; // OK: it doesn't modify the value of 'p' itself but the value of the integer pointed by 'p'
}
};
I believe that that const functions are functions that can be invoked on objects declared as const.
It doesn't stop you from changing the state of the object in the function.
For example:
1 2 3
const Complex c;
c++; // this will not throw a compile-time error in the above code,
// even though it doesn't make sense to change a const object's state!
FYI: generally, the prefix operator++(void) adds then returns, and the postfix operator++(int) adds but returns the old value.
I cannot change the value of my pointer real, if there is "const" after definition.
My mistake was that I was trying to change *real thinking that I'm changing real (the pointer),
but it is no true, I was just changing the value of the object that it was pointed to.
But in order to change my pointer real I should have done it like this:
1 2
double p;
real = &p;
In this case I cannot do it, because of "const" and because now I'm really changing my
pointer:
I understand it, but could you show more specific example of using
"const" before method definition. I cannot understand why you need to use
it at all....
The constant might be at the front of the function definition/declaration - but as I say it is related to the object being returned by the function and has not effect on the function itself.