In a project, I have a class hierarchy implementing a graph with levels of hierarchy (that is, a graph node can be a graph itself — think of it as an electronic circuit where a gate can actually be an integrated chip, for instance). Thus, I have some class Base
derived into Group
and Leaf
, and the class Base
has an attribute ancestor
, which I would like to be able to set from a given method of Group
(when adding a child), but not from anywhere else:
class Group;
class Base {
private: // or protected?
Group* ancestor;
};
class Group : public Base {
private:
void setAncestor(Base* child) {
// Something like
child->ancestor = this;
}
};
class Leaf : public Base {
// ...
};
What would be the "correct" way to achieve that? Usually, I would use friend
methods, but it seems to me that this is impossible in this context, since I would have to declare friend Group::setAncestor
in Base
, which must be declared before. (Also note that those declarations are in different files in the real code.)