I want to ask a question about copy reference operators.
I have the following class named Mystring
and I have a copy reference operator for it, which works.
#ifndef _MY_STRING_
#define _MY_STRING_
class Mystring
{
private:
char *str; // pointer to a char[] that holds a c-style string
public:
Mystring(); // no args
Mystring(const char *s); // overloaded
Mystring(const Mystring &source); // copy
~Mystring(); // destructor
Mystring &operator=(const Mystring &rhs);// overloaded copy assignment operator
void display() const; // getters
int get_length() const;
const char *get_str() const; // pointer is returned
};
#endif // _MY_STRING_
and this is the copy reference operator function:
// Overloaded assignment copy operator
Mystring &Mystring::operator = (const Mystring &rhs) {
std::cout << "Copy assignment" << std::endl;
if (this == &rhs) // check the pointer is on the same address of rhs i.e. & = reference operator
return *this; // returns the reference
delete [] this->str;
str = new char [std::strlen(rhs.str) + 1];
std::strcpy(this->str, rhs.str);
return *this;
}
I'm a beginner in C++ so this is confusing but I'll try to describe what happens.
I'm aware that there is a this
operator, which acts as a pointer. When dereferenced, it allows us to work with the object itself.
From the first line
Mystring &Mystring::operator = (const Mystring &rhs)
I can see that I will have an operator function that returns a reference, as the &
operator exists in the declaration.
However, at the end of the if statement and the overall function, we state
return *this
although if we are dereferencing this
, we're returning the object and not the reference as per my explanation above.
Microsoft c++ documentation also states
The expression
*this
is commonly used to return the current object from a member function:
To clarify, this
is a pointer to a current object so *this
and then returning it should mean that i'm returning the object, not another reference.
What mistake am I making in my understanding of this code?