Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ proper usage, this pointer [duplicate]

Tags:

c++

this

Possible Duplicate:
When should I make explicit use of the this pointer?

I'm wondering about the proper usage of the "this" pointer.

I've seen someone create a class constructor with the argument passed variable passed in named 'data'. However he had a private member variable named 'data' already thus he simply used:

this->data = data;

would have worked to simply use

data = data_in

(if the parameter was named data_in), and no need to invoke the "this" pointer and reference the member type.

Now I'm wondering, is this proper usage? Using this->member to reduce on naming complexity? I mean it works and I see that it accomplishes what was intended but I'm wondering if some of you more experienced C++ guys and girls can say a word or two if this is common practice?

Also, out of curiosity I've instrumented the code just to see what happens under the hood, and it seems the "this" pointer is invoked anyhow. I guess that's the way references to the class object are done anyways.

like image 636
janjust Avatar asked Feb 22 '23 09:02

janjust


1 Answers

In most cases, specifically dereferencing the this pointer to access a non-static data-member of the class instance is unnecessary, but it can help with naming confusion, especially when the data-members of the class are defined in a separate header file from the code-module. However, it is necessary to use the this pointer if you are accessing a non-static data-member that is a member of a base-class that is a templated class. In other words, in a situation like:

template<typename T>
class base_class
{
    protected:
        int a;
};

template<typename T>
class derived_class : public base_class<T>
{
    void function()
    {
        a = 5; //this won't work
        this->a = 5; //this will work
    }
};

you'll note that you must use the this pointer in order to properly resolve the inherited non-static data-member from the template base-class. This is due to the fact that base_class<T>::a is a dependent name, in this case dependent on the template parameter T, but when used without the this pointer, it is treated as a non-dependent name, and is therefore not looked up in the dependent base-class namespace. Thus without the specific dereference of the this pointer, you'll end up with a compiler error like "a was not declared in this scope", or something similar.

like image 153
Jason Avatar answered Mar 07 '23 11:03

Jason