Background:
I am reading code written by someone else, and I am fairly new to C++ programming. When I look at the classes written by that person, and the corresponding member functions, I get confused with the usage of the this
pointer. In some member functions this
is used and in others not.
Why is that the case?
I know it is a very common confusion for the ones who start doing C++ recently.
Code Snippets:
The class:
class InitTable {
public:
InitTable();
virtual ~InitTable();
void clearTable();
void addEntry(std::string sumoID);
void deleteEntry(std::string sumoID);
InitEntry* getEntry(std::string sumoID);
IPv4Address getEntryIPaddress(std::string sumoID);
protected:
std::map<std::string, InitEntry*> table;
};
Member function (with this
):
void InitTable::clearTable()
{
this->table.clear();
}
Member function (without this
):
void InitTable::deleteEntry(std::string sumoID)
{
InitEntry* ie = getEntry(sumoID);
if (ie != NULL)
{
table.erase(sumoID);
delete ie;
}
}
Question:
Note that in void InitTable::clearTable()
, this->table.clear()
is used and in void InitTable::deleteEntry()
, table.erase()
only table
without this
is used.
void InitTable::clearTable()
{
table.clear(); // no "this"
}
What is the trick in here? What would be the behaviour if this->table.erase()
would be used instead.
void InitTable::deleteEntry(std::string sumoID)
{
InitEntry* ie = getEntry(sumoID);
if (ie != NULL)
{
this->table.erase(sumoID); // "this" added
delete ie;
}
}
As I said, I'm a bit of n00b so a thorough description with minimal example would be very helpful.