Luchian Grigore
Luchian Grigore

Reputation: 258558

Operator [] overloading

I have the following code:

class A
{
    public:
    A() {};
    void operator[](int x)
    {
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    A a;
    a.operator[](0);
    a[0];
}

Both calls work, but I want to know whether there is any difference. Is one more efficient than the other? Do other things happen(besides executing the code in the overloaded operator) in either case?

EDIT: Is there a case why you would want to write a.operator instead of just []. What's the point of overloading if you're not using the short syntax?

Upvotes: 4

Views: 287

Answers (5)

Seb Holzapfel
Seb Holzapfel

Reputation: 3873

The explicit operator[] (and any other explicit operator) is used in an inheritence heirarchy, where you are trying to call operator[] on a base class. You can't do that using the normal [], as it would result in a recursive function call. ie; you might use something like this:

struct Base {
    void operator[] (int i) { }
};

struct Derived : public Base {
    void operator[] (int i) 
        { Base::operator[](i); }
};

Upvotes: 4

iammilind
iammilind

Reputation: 69978

No there is no difference between both versions from performance point of view. a[0] is more readable.

Also, the operator [] is typically defined as,

Type& operator[](const int x)
{
  return v[x];  // Type 'v' is member variable which you are accessing for array
}

Upvotes: 1

sharptooth
sharptooth

Reputation: 170479

They are completely equivalent - just in once case C++ adds syntactic sugar that makes your code prettier. You can call all overloaded operators explicitly - the effect will be the same as when they are called implicitly and the compiler redirects calls to them.

Upvotes: 1

foxy
foxy

Reputation: 7672

Other than having to type another 11 characters, there is no functional difference between the two.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 476950

Both calls are identical. All the operators can be called with an explicit .operator## syntax, where ## stands for the actual operator symbol.

It is the literal operators like a + b that are just syntactic sugar for a.operator+(b) when it comes to classes. (Though of course for primitive types that is not the case.)

Note that your []-operator is not very typical, since it is usually used to return a reference to something -- but it's up to you how to implement it. You're restricted to one single argument, though, unlike operator().

Upvotes: 5

Related Questions