ryeguy00
ryeguy00

Reputation: 27

Pointers within class methods

How do I make a pointer within a method of a class point to the object that the method is being called on?

I want to define a pointer in the body of a public method of a class and have it point to the instance of the object that the method is being called on.

Here's my code for some more context:

void Node::print() {
    Node *temp = this; //points to the node that calls the print function

    while (temp->next != NULL) {
        cout << "Name:  " << temp->name << "\tID:  " << temp->ID << endl;
        temp = temp->next; //makes temp->next point to the next node in the list.
    }

    //this line runs when temp->next == NULL
    cout << "Name:  " << temp->name << "\tID:  " << temp->ID << endl;
}

Upvotes: 0

Views: 100

Answers (1)

P.W
P.W

Reputation: 26800

The documentation of this pretty much describes what you are looking for:

The keyword this is a prvalue expression whose value is the address of the object, on which the member function is being called.

Upvotes: 7

Related Questions