Thread: What is the difference between operator and function?

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    225

    What is the difference between operator and function?

    Hello,
    this has been a doubt of mine since quite few days. Please tell me the difference between operators and functions?i mean some may say functions have () and operators dont have () but it's wrong sizeof is operator and it has braces like sizeof(c) where c is some data type

    So please explain me i am little confused

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    They are both functions (when it comes to operator overloading), except that operators are normally called with a different syntax. For class objects it is also possible to call overloaded operators with function-syntax:
    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    
    int main()
    {
        string a = "Hello ", b = "world";
        string c = operator+(a, b);
        cout << c;
        return 0;
    }
    sizeof is a slightly different operator as it is evaluated at compile time, and by the way - you don't need to use () around the type. You can use it without any brackets, or put the brackets around sizeof instead (unless in a compound statement brackets are needed).

    In addition, there is also operator() that allows you to "call" an object as if it was a function
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    operator list is fixed, you cannot create new operator or change the name of the existing, or change the parameter list

    functions could be added freely, you can create funtion with arbitrary name, list of parameters and return values
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed