-
Pointer syntax ->
Hello, I was studying for my exam and came across with a pointer syntax I had never came across with ("this->"). I made some research about it but I didn't really understand it's meaning.
If I'm correct "return (*this);" would return the object of the class but I have no idea how "this->" is used in the context below in the class constructor.
Code:
class Message {
friend ostream& operator<<(ostream& os, Message& message);
private:
time_t date; //time_t is an unsigned integer
string content;
public:
Message(time_t date, string content);
time_t getDate() const;
string getContent() const;
};
Message::Message(time_t date, string content)
{
this->date = date;
this->content = content;
}
I would have probably defined the constructor as follows:
Code:
Message::Message(time_t date, string content)
{
date = date;
content = content;
}
so I don't really understand what is the difference between them.
Can anyone give me a brief explanation about this subject? Thanks in advance.
-
this is a pointer to the current object of a class. The arrow operator is a syntactic convenience.
is functionally identical to
-
this->date will look get the variable "date" that's part of the underling class. Without it, the variable clashes with the like named parameter "date", so your version of the constructor doesn't work.
Another way to write this constructor follows. This will do the right thing without the explicit "this->".
Code:
Message::Message(time_t date, string content) :date(date),content(content){}
-
I don't know if one should recommend naming parameters in the constructors the same as member variables. Some compilers (like clang, unsure about gcc) will give warnings for this.