Search code examples
c++this

*this vs this in C++


I understand what this does, but what is the difference between *this and this?

Yes, I have Googled and read over *this in my text book, but I just don't get it...


Solution

  • 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.