0

I Need To Do Combination of Operator Overloading in my code.

For example :

When I write x[i] it returns a value, this much I know. What I need to know, is how to make the operator function so that if it's alone, it returns the value inside, and if it's followed by equal (x[i] = val) it sets the value of x[i].

Reto Koradi
  • 53,228
  • 8
  • 93
  • 133
Naggar
  • 283
  • 1
  • 2
  • 10
  • Ever heard of punctuation? – Phonon Apr 27 '14 at 02:27
  • I'm not sure quite what you're asking, but [operator overloading](http://stackoverflow.com/questions/4421706/operator-overloading)? – chris Apr 27 '14 at 02:28
  • 1
    You'll need to return either an lvalue reference or a proxy class. Which depends on how the type of `x` is set up and what those expressions need to do. – aschepler Apr 27 '14 at 02:30

1 Answers1

1

You're misunderstanding what happens in the statement x[i] = val. Assume your operator overload looks like this:

item_type & operator[](int index);

Then the [] operator is returning a reference to some object of type item_type. So we can replace x[i] with:

(item_type &) = val

The = operator is thus applied to the value of item_type &, not the original x type. If item_type supplies an assignment operator, then this works. If it doesn't, then it doesn't.

aruisdante
  • 8,875
  • 2
  • 30
  • 37
  • U Mean That when I use x[i] = val , it'll understand that the target is x[i] not x ?? – Naggar Apr 27 '14 at 03:44
  • Yes, because ``x[i]`` will be evaluated before ``=`` is. – aruisdante Apr 27 '14 at 03:54
  • but what if the implementation of the overloaded operator as this; in which the existence of the operator after the object will lead to returning a value example : http://codepad.org/fFYysePI – Naggar Apr 27 '14 at 04:00
  • When i try to assign a value to it , the IDE tells me that the x[i] not required to be left operand , but it must be in the R.H.S. – Naggar Apr 27 '14 at 04:03
  • In your example the return needs to be ``T &`` if you want it to mutate the value stored in ``x``. Otherwise you're just mutating a copy that's created as the return for the operator. Also having a default return of 0 for a templated return type of ``T`` is invalid if ``T`` is not castable to ``int``. It needs to either throw an exception or have undefined behavior (such as returning ``T()``, which could do anything including be a compile-time failure). – aruisdante Apr 27 '14 at 04:57
  • [This is a handy-dandy reference](http://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading#Subscript_operator) for operator overloading in general in C++ (jumped to the subscript operator) – aruisdante Apr 27 '14 at 05:06