I'm trying to access a protected member of a class defined and implemented by an external library. I'd like to achieve that without copying or moving the instance if possible.
Here is a simplified example. Let's say this is the code from the external library:
// some_external_library.h
class Node {
public:
static Node Create();
protected:
Node(int val) : val_(val) {}
int val_;
};
This is what I am trying to do:
// my_code.cpp
#include "some_external_library.h"
Node node = Node::Create();
int val = node.val_; // <-- This is invalid since val_ is protected.
Node
class is part of some external library that I link to my program. So, I'd like to avoid modifying Node
class by adding a public function or friend declaration for accessing val_
. Also, I'd like to avoid creating a copy of node
object or moving from it, so I'd like to avoid creating a derived class moving/copying the Node
instance just to access a member field. Is it possible?
I came up with a possible solution, which worked fine for the minimal example:
// my_code.cpp
#include "some_external_library.h"
class NodeAccessor : public Node {
public:
int val() const { return val_; }
};
Node node = Node::Create();
int val = static_cast<const NodeAccessor&>(node).val();
However, I'm not sure if this is valid since node
isn't an instance of NodeAccessor
. Is this standard compliant? Would it cause any problems (e.g. optimizing away of val_
during compilation of the external library)?