Re: How to check if another object is my superclass from a function
in an even higher superclass?
On 3 mrt, 11:10, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
bart van deenen wrote:
Hi
I have a pile of objects all derived from one baseclass, and I want to
have a generic function that an object can use to see if another
object is its superclass.
[snip: something using __typeof__]
I now know more about the function of the __typeof__ operator, so I
understand why it doesn't work.
First, __typeof__ does not exists in standard C++. There is a typeof
operator, though.
But how would you do this? Is there an elegant way?
Well, for starters, there is the use of virtual functions:
class Base {
protected:
virtual
bool do_check ( Base * ptr ) {
return ( true );
}
public:
bool subclass ( Base * ptr ) {
return do_check( ptr );
}
bool superclass ( Base * ptr ) {
return ptr->do_check( this );
}
};
class D1 : public Base {
bool do_check ( Base * ptr ) {
return ( dynamic_cast< D1* >( ptr ) );
}
};
class D2 : public D1 {
bool do_check ( Base * ptr ) {
return ( dynamic_cast< D2* >( ptr ) );
}
};
class D3 : public Base {
bool do_check ( Base * ptr ) {
return ( dynamic_cast< D3* >( ptr ) );
}
};
....
The next observation is that do_check() looks more or less alike in all
derived classes. In that regard, it is like a clone() function. There is =
a
recent thread about how to fold this code into a policy or at least make
sure that each derived class implements the method.
BTW: I don't know very much about object oriented programming, but from w=
hat
I hear, the need for a function like superclass() or subclass() is a desi=
gn
smell. What is the underlying problem that you have to solve?
Thanks for your answer
My problem: I have a tree of displayable objects of different types.
These object types have an class inheritance tree, and also have the
capability to inherit attributes from their ancestor objects (in the
tree, not in the class hierarchy). A bit like html and css.
Now one of my nested objects might inherit an attribute (say 'color')
and it will have to loop through its ancestors to find one that can
provide it with the attribute 'color', but not all of its tree
ancestors might be part of its own class inheritance path, so it won't
even ask those if they have the attribute value available.
So my reasoning is that by asking another tree object if its part of
my class inheritance, is that if it says no, i don't have to ask it
for the 'color' attribute.
Hope this makes sense.