Overloading operator in C++ and dereference

c++, operator-overloading

Solution

String* moj = new String("Alice has a cat");
cout<<(*moj)[2]; // IT WORKS BUI
//  cout<<moj[2]; //I WOULD LIKE TO USE THIS ONE

That can't be done, the subscript operator in the later case is applied to a pointer. It is only possible to overload operators when at least one of the arguments is of user defined type (or a reference to it, but not a pointer); in this particular case the arguments are `String*` and `2`, both fundamental types.

What you may do is drop the pointer altogether, I don't see why you need it:

String moj("Alice has a cat");
// cout<<(*moj)[2]; <-- now this doesn't work
cout<<moj[2]; // <-- but this does

Problem

I am practicing overloading operators in C++ right now and I have a problem. I created String class, it has just to fields one is char array other is length. I have a String "Alice has a cat" and when I call ``` cout<<moj[2]; ``` I would like to get 'i', but now I am getting moj + 16u adress of moj + 2 sizeof(String) When I call ``` cout<<(*moj)[2]; ``` it works as it shoud but I would like to dereference it in overloaded operator definition. I tried many things but I can't find solution. Please correct me. ``` char & operator[](int el) {return napis[el];} const char & operator[](int el) const {return napis[el];} ``` AND the whole code, the important things are down the page. It's compiling and working. ``` #include <iostream> #include <cstdio> #include <stdio.h> #include <cstring> using namespace std; class String{ public: //THIS IS UNIMPORTANT------------------------------------------------------------------------------ char* napis; int dlugosc; String(char* napis){ this->napis = new char[20]; //this->napis = napis; memcpy(this->napis,napis,12); this->dlugosc = this->length(); } String(const String& obiekt){ int wrt = obiekt.dlugosc*sizeof(char); //cout<<"before memcpy"<<endl; this->napis = new char[wrt]; memcpy(this->napis,obiekt.napis,wrt); //cout<<"after memcpy"<<endl; this->dlugosc = wrt/sizeof(char); } ~String(){ delete[] this->napis; } int length(){ int i = 0; while(napis[i] != '\0'){ i++; } return i; } void show(){ cout<<napis<<" dlugosc = "<<dlugosc<<endl; } //THIS IS IMPORTANT char & operator[](int el) {return napis[el];} const char & operator[](int el) const {return napis[el];} }; int main() { String* moj = new String("Alice has a cat"); cout<<(*moj)[2]; // IT WORKS BUI // cout<<moj[2]; //I WOULD LIKE TO USE THIS ONE return 0; } ```

Original source