1

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???);
}
JoshAsh
  • 37
  • 8

2 Answers2

3

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

Uduru
  • 511
  • 2
  • 10
2

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);
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116