Thread: operator overloading ()

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    113

    operator overloading ()

    hi, Im tryin to overload the () operator for arrays operations.
    to create a rvalue
    to use like
    Code:
    int main()
    {
         //this is not a const object so why i need a const member fucntion?
         
         Array a1(5,5);    
         
        cout << a1(1,2) //print element 1,2 .
    }
    I need to declare the function that way:
    Code:
    const int &MyClass::operator()(int,int)const.
    why I need to make this function const??(I mean the last const)
    please any clear explanation why should i do this that way?
    if i dont write the last const the compiler generates an error message.

    thanks for any help

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    What error message?
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Mar 2004
    Posts
    113
    here is it

    23 C:\programas c++\ejer8_13\arreglos3.h
    `const int& Arreglo:perator()(int, int)' and `int& Arreglo:perator()(int, int)' cannot be overloaded

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    There are two variations of the operator. One is normal, returns a reference to an element and thus allows the array to be modified. The other returns a const reference and doesn't allow the array to be modified. It takes the same arguments though, and so can't be distinguished from the first. Because it doesn't allow modification of the array, it is suitable for a constant instance of the class, which you indicate by the const at the end. This also makes it distinguishable from the first overload.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  5. #5
    Registered User
    Join Date
    Mar 2004
    Posts
    113
    very clear CornedBee
    thanks a lot

Popular pages Recent additions subscribe to a feed