taking address of protected base member function not possible?? what to do?
Hi!
I have a class hierachy whose objects at runtime make up a tree
structure. There are two important classes in this hierachy. First there
is a common base for all classes. Second there is a derived "container
base" class which provides basic container features such as owning
children. In fact there are more classes, but I omitted them for this post.
struct Base {...}; // 1
struct ContainerBase : Base {...}; // 2
Within this tree I want to enumerate all objects in a pre-order tree
walk. The Base class has an "unsigned id" attribute which is to be
assigned numbers starting from 1. I introduced a virtual method in Base
which is to be redefined in derived classes according to their children.
This method is declared protected because the user shall not call it
directly.
struct Base
{
virtual ~Base() {}
unsigned getID() const { return id; }
protected:
unsigned id;
virtual void assignIDs(unsigned &counter) =0;
};
The container base class has to assign to its own "id" and then call
assignIDs recursively for all children:
struct ContainerBase : Base
{
protected:
virtual void assignIDs(unsigned &counter)
{
using namespace boost;
//own id:
id = counter++;
//recurse:
//**ERROR**: cannot take address:
std::for_each(children.begin(), children.end(),
bind(&Base::assignIDs, _1, ref(counter))); }
boost::ptr_deque<Base> children;
};
I want to take the address of the Base::assignIDs virtual function, but
I'm not allowed to. I already read the post "Calling a parent class's
protected function from another instance of the class", Feb 19th, but
things discussed there do not apply here: I cannot use
"&ContainerBase::assignIDs" because I need to call the function on the
static type "Base&". This is why an explicit for-loop will not work here
neither.
To circumvent the problem I added a Base::giveAddressOfAssignIDs()
function which returns the address &Base::assignIDs. This way I can use
the for_each and bind construct. But I think the giveAddress function is
quite ugly. Are there other means to call the base virtual function for
all children? I cannot have the functions public!
Frank
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]