Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use "this" pointer in member function [duplicate]

Tags:

c++

this

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.

like image 719
cross Avatar asked Dec 18 '25 05:12

cross


1 Answers

It is never required inside a normal function, unless there is a parameter with the same name as a member. In a constructor you can use an initalizer list to prevent ambiguity. The use of a this pointer might be required when you use templates.

like image 123
tillaert Avatar answered Dec 19 '25 17:12

tillaert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!