Operator overload () ,confusion

Hi ,I am a little confuse about this const(what exactly mean)
Where to use it and when

1
2
3
4
 int operator()(int i)const
  {
      return i+5;
  }
closed account (zb0S216C)
Lio wrote:
I am a little confuse about this const

When const is used in this context, it means the method is read-only, which basically means the method cannot alter any non-mutable data member. In other words, if a data member isn't declared mutable, operator( ) can't modify it. Read-only methods can only call read-only methods. Finally, the displayed definition is only valid within a class scope.

Edit:
I mentioned mutable. Here's an example:

1
2
3
4
5
6
7
8
9
10
11
class Example
{
    private:
        mutable int Member_;

    public:
        Example &operator ( ) ( ) const // Read-only
        {
            this->Member_ = 10;
        }
};

The mutable keyword can only appear in a class member declaration. The keyword indicates that the member can be modified through read-only methods.

Additional Edit:

You also asked for scenarios when it would be used. When the class in which a read-only method is defined is instantiated and declared constant, the compiler will invoke (call) the read-only version of the method (if it exists). Consider this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

class Example
{
    public:
        const Example &operator( ) ( ) const
        {
            std::cout << "Example::operator( ) const" << std::endl;
            return( *this );
        }

        Example &operator( ) ( )
        {
            std::cout << "Example::operator( )" << std::endl;
            return( *this );
        }
};

int main( )
{
    const ::Example Example_Const;
    Example_Const( );

    ::Example Example_Non_Const;
    Example_Non_Const( );

    return( 0 );
}

Execute this code and see what happens.

Wazzak
Last edited on
Well,
With g++ and with clang, I get an error requiring Example_Const initialization.
Was this a trick question?
vin
closed account (zb0S216C)
Vince59 wrote:
Was this a trick question?

No, the position const in the OP's code is a valid location.

Wazzak
Topic archived. No new replies allowed.