Search code examples
c++classobjectpointersthis

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???);
}

Solution

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