I'm learning C++ and this week I try to understand the operator overloading, no problems so far. Now I reached overloading the index operator and I managed it as follows,
std::string &operator[](size_t index);
std::string const &operator[](size_t index) const;
However, in several threads I read it is better to use a Proxy class, so I tried to implement a Proxy class and here the trouble starts. Note that I just implement the Proxy class in this simple class to understand how a Proxy class is working. I have already overloaded all functions without Proxy class and think it is time for the next step.
I have a class Strings which contains a pointer to several string objects. Suppose we have a object of the class Strings, called str, then I want to be able to use str[i] to get the i-th string and str[i][j] to get the j-th letter of the i-th string. Therefore I implemented a operator overloading in the Proxy class for [] and for <<, these are working fine.
Next, I want to be able to say str[i] = str[j], and therefore I implemented the operator=, however I am not able to get this right. Do you see what I'm doing wrong? There is no compile error, but the value isn't updated after calling str[i] = str[j].
And a subquestion, is the Proxy class implemented correct? It is working but I would also like to learn to use the language in a correct way.
Just to avoid confusion: I understand that this is much easier with a vector and that a Proxy class is not needed here. However, I want to understand how a Proxy class works and in my point of view it is best to start implementing it in a very simple class.
class Strings
{
std::string *d_str;
public:
Strings();
Strings(int argc, char *argv[]);
// Some other functions
// ...
// End other functions
class Proxy {
std::string d_string;
public:
Proxy(std::string &str): d_string(str) {}
char &operator[](int j) { return d_string[j]; }
friend std::ostream &operator<<(std::ostream &out, Proxy const &rhs)
{
out << rhs.d_string << '\n';
return out;
}
Proxy &operator=(Proxy const &other)
{
d_string = other.d_string;
return *this;
}
};
Proxy operator[](size_t idx)
{
return Proxy(d_str[idx]);
}
private:
//More functions here
};