I am making a tree-based data structure where there is one immutable root and each node is assigned a parent that never changes. Each node requires a reference to the parent.
I decided to use references instead of pointers, and came up with the following attempt to check if a particular node is the root:
#include <cstdio>
class Obj {
public:
Obj &parent;
Obj(Obj &parent) : parent(parent) {}
int hasparent();
};
int Obj::hasparent()
{
return &parent != this;
}
int main()
{
Obj base(base);
Obj child(base);
printf("base.hasparent = %d\n", base.hasparent());
printf("child.hasparent = %d\n", child.hasparent());
printf("child.parent.hasparent = %d\n", child.parent.hasparent());
}
I would like your critique. Is this correct? Being unfamiliar with C++, I am actually surprised that the compiler allowed me to pass a reference to an object that I didn't construct yet. Is this the right approach?