this is a pointer

Published

2023-08-05

In our introduction to C++ you saw the use of this, e.g.,

this->name = name;

Just to be clear (now that we’ve seen pointers): [this] is a pointer the current object. Here’s a little bit of code that bears that out.

#include <iostream>

class Foo {
public:
    Foo() {};
    Foo* getThis() {  // return the value of this
        return this;
    }
};

int main() {
    Foo f = Foo();    
    std::cout << f.getThis() << std::endl;    
    // Prints an address like 0x7ffee827a7c8 or similar    
    // `this` is a pointer!
    return 0;
}

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

All materials copyright © 2020–2023, The University of Vermont. All rights reserved.