The following code would not compile because apparently that's how protected members work. (There are questions answering the why on SO, eg. here).
class Parent {
protected:
int value;
};
class Child : public Parent {
public:
void set_value_of(Parent* x, int value) {
x->value = value;
}
};
int main() {
}
For example, GCC reports
main.cpp: In member function 'void Child::set_value_of(Parent*, int)':
main.cpp:11:16: error: 'int Parent::value' is protected within this context
x->value = value;
^~~~~
main.cpp:5:13: note: declared protected here
int value;
^~~~~
What could possibly go wrong if you cast x
to Child
? Is it a case of never ever do it or you can, if you know what you're doing?
void set_value_of(Parent* x, int value) {
static_cast<Child*>(x)->value = value;
}
Edit Unfortunately all suggestions for getting around this abuse so far do not help me in solving my design problem, thus I try to be less generic and show my actualy real-world case.
The main goal is to not rely on friend
declaration, as the Node
class should not need to be modified (ie. no friend declaration should need to be added), to implement another subclass like Group
.
class Node {
protected:
Node* _parent;
};
class Group : public Node {
protected:
std::vector<Node*> _nodes;
public:
void insert(Node* node) {
if (node->_parent) {
throw std::runtime_error("node already has a parent");
}
_nodes.push_back(node);
node->_parent = this;
}
};
This could be solved by add friend class Group
to the Node
class, but I am looking for a way around it.