Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Overloading [] from left and right

I'm trying to think how can I overload [] from both left and right to function as set and get for a custom string class I'm working on. for example:

char x= objAr[1]; //get
objAr[2]='a'; //set

The string class basically looks like this:

class String {
private:
    char* data;
    unsigned int dataSize;
public:
    String();
    String(char);
    String(char*);
    String(String&);
    ~String();
    char* getData();
    int getSize();
};
like image 905
Adam Mo Avatar asked Feb 21 '26 15:02

Adam Mo


1 Answers

If you always have the data to back it up, you can return a reference:

char& String::operator[] (size_t idx)
{ return data[idx]; }

char String::operator[] (size_t idx) const
{ return data[idx]; }

In your case, that should be sufficient. However, if this was not option for whatever reason (e.g. if the data is not always of the proper type), you could also return a proxy object:

class String
{
  void setChar(size_t idx, char c);
  char getChar(size_t idx);

  class CharProxy
  {
    size_t idx;
    String *str;
  public:
    operator char() const { return str->getChar(idx); }
    void operator= (char c) { str->setChar(idx, c); }
  };

public:
  CharProxy operator[] (size_t idx)
  { return CharProxy{idx, this}; }

  const CharProxy operator[] (size_t idx) const
  { return CharProxy{idx, this}; }
};

This would also enable you to do things like implicit data sharing with copy-on-write.

like image 182
Angew is no longer proud of SO Avatar answered Feb 24 '26 07:02

Angew is no longer proud of SO