JoshAsh
JoshAsh

Reputation: 37

use a pointer to the current object - C++

just wondering how to use (pass or return) a pointer to the current object in c++?

in my case I have a map of nodes, and I want to assign a node a child, and in doing so have the current node be added as a parent to the child

below is what I have right now

void node::assign_child(node* child)
{
   children.push_back(child);
   child->parents.push_back(*this???);
}

Upvotes: 1

Views: 381

Answers (2)

Uduru
Uduru

Reputation: 518

Well, this itself is a pointer, named as "the this pointer".

About why is it a pointer, This SO post might be helpful.

Or just look at what the C++17 Standard says.
§12.2.2.1 The this pointer stands:

the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*.

Upvotes: 3

Silvio Mayolo
Silvio Mayolo

Reputation: 70287

Very close, but this is itself a pointer. You don't want to dereference this or else you'll just get a value.

child->parents.push_back(this);

Upvotes: 2

Related Questions