Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*this vs this in C++

Tags:

c++

this

People also ask

What is difference between * and & in C?

With the * operator, I make a new variable, which is allocated a place in memory. So as to not unnecessarily duplicate variables and their values, the & operator is used in passing values to methods and such and it actually points to the original instance of the variable, as opposed to making new copies...

What does * this return?

this means pointer to the object, so *this is an object. So you are returning an object ie, *this returns a reference to the object.

What are * and & operator means?

Answer: * Operator is used as pointer to a variable. Example: * a where * is pointer to the variable a. & operator is used to get the address of the variable. Example: &a will give address of a.


this is a pointer, and *this is a dereferenced pointer.

If you had a function that returned this, it would be a pointer to the current object, while a function that returned *this would be a "clone" of the current object, allocated on the stack -- unless you have specified the return type of the method to return a reference.

A simple program that shows the difference between operating on copies and references:

#include <iostream>

class Foo
{
    public:
        Foo()
        {
            this->value = 0;
        }

        Foo get_copy()
        {
            return *this;
        }

        Foo& get_copy_as_reference()
        {
            return *this;
        }

        Foo* get_pointer()
        {
            return this;
        }

        void increment()
        {
            this->value++;
        }

        void print_value()
        {
            std::cout << this->value << std::endl;
        }

    private:
        int value;
};

int main()
{
    Foo foo;
    foo.increment();
    foo.print_value();

    foo.get_copy().increment();
    foo.print_value();

    foo.get_copy_as_reference().increment();
    foo.print_value();

    foo.get_pointer()->increment();
    foo.print_value();

    return 0;
}

Output:

1
1
2
3

You can see that when we operate on a copy of our local object, the changes don't persist (because it's a different object entirely), but operating on a reference or pointer does persist the changes.


this is a pointer to the instance of the class. *this is a reference to the same. They are different in the same way that int* i_ptr and int& i_ref are different.