[ ] operator overloaded

Started by
3 comments, last by vbisme 22 years, 1 month ago
Sorry, can anyone explain to me how the offset [ ] operator works when it is overloaded?
Advertisement
  class YourClass{	NODETYPE thearray[somesize];public://...NODETYPE operator[](u32 Index){	// do some assertion check for in range	// ..	return(thearray[Index]);}};  

NODETYPE is whatever you want it to be.

Watch out for :
  YourClass inst1,inst2,*ptrinst=&inst1NODETYPE k = inst[3]; // correctNODETYPE i = ptrinst[3]; // wrong , indexing pointer array NODETYPE j= (*ptrinst)[3]; // correct, indexing YourClass instance.  


if you want to do :

inst1[3] = somevalue,

you need to past back a reference from the operator[]. then the operator= is called on the returned reference. But beware this allows things to muck about with the internal values. Better to use a Set( index, value ) function.
quote:Original post by Mark Duffill
you need to past back a reference from the operator[].


/me thinks you forgot the & for the return value of operator[] in your source to make it a reference

Should be
NODETYPE & operator[](u32 Index)... 


Bye, VizOne
Andre Loker | Personal blog on .NET
Note my comment at the bottom,
quote:
if you want to do :

inst1[3] = somevalue,

you need to past back a reference from the operator[]. then the operator= is called on the returned reference. But beware this allows things to muck about with the internal values. Better to use a Set( index, value ) function.



I left it out on purpose,

NODETYPE operator[](u32 Index ){}
Will return by copy constructor, meaning:-

u32 array[n];
u32 i = array[m];
i = 3;
Modifying i won't change the array contents.

But using
NODETYPE &operator[](u32 Index){}
Will return by reference, which in essance is:-

u32 array[n];
u32 *i = &array[m];
(*i) = 3;
so modifying contents of i directly modifies the contents of the array which may be unsafe,(after all a class is *supposed* to protect the data from this external fiddling!).

References are useful, but you have to be carful what gets access to them!


Edited by - Mark Duffill on February 26, 2002 4:05:36 AM
Then you should probably return a const reference; it'll give you similar protection while also being very efficient. Also, if you want to you can make a const and non-const [] operator so the operator works as either an l or r-value (const or non-const):

  class YourClass{	 NODETYPE thearray[ somesize ];public: //... const NODETYPE& operator [] ( u32 Index ) const  {  // do some assertion check for in range  return thearray[ Index ];  } NODETYPE& operator [] ( u32 Index )  {  // do some assertion check for in range  return thearray[ Index ];  }};  


--
Eric

[Edits] Goofing around with formatting tags

Edited by - ekenslow on February 26, 2002 3:12:12 PM
-- Eric

This topic is closed to new replies.

Advertisement