0
class Node {
public:
    int key;
    Node *parent;
    std::vector<Node *> children;

    Node() {
      this->parent = NULL;
    }

    void setParent(Node *theParent) {
      parent = theParent;
      parent->children.push_back(this); // I can't understand this.
    }
};

In the function setParent, in parent->children.push_back(this), why do we pass this as the parameter and what will it do?

  • [this](https://en.cppreference.com/w/cpp/language/this) is basically a pointer to the calling object. – kesarling He-Him Jul 15 '20 at 03:40
  • 1
    Does this answer your question? [What is the 'this' pointer?](https://stackoverflow.com/questions/16492736/what-is-the-this-pointer) – xavc Jul 15 '20 at 03:43
  • Does this answer your question? [What is the 'this' pointer?](https://stackoverflow.com/questions/16492736/what-is-the-this-pointer) – kesarling He-Him Jul 15 '20 at 03:43

1 Answers1

2

The this pointer is a pointer to the object whose member function is currently executing. That line of code adds this node to its parent's vector of children. That makes sense because this node is one of its parent's children.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278