Best practice when accesessing derived classes in a QList - c++

I have a base model where I have implemented the virtual members of QAbstractItemModel. I then use my base model in my project as needed by deriving new classes with specifics.
class BaseModel : public QAbstractItemModel{
public:
...
protected:
QList<BaseItem*> list;
}
class DerivedModel : public BaseModel{
public:
...
}
class DerivedItem : public BaseItem{
public:
...
}
My derived model uses DerivedItem objects to store data which have some specifics that BaseItem doesn't have. They are stored in list. Methods in BaseModel uses objects in list as well.
My issues is because of this I have to type cast every time I access objects from list in the derived model. And I can't use macros like foreach.
Is there any tips or tricks I can use in this circumstance that will enable me to use macros and prevent me from type casting every time I access items from the list. Or is there another method (better practice) when making a common class to later derive from.
Thanks,

when BaseItem has virtual methods and DerivedItem does only overwrite the existing members of BaseItem you should be able to call
foreach(BaseItem* item, list){
item->foo();
}
because of polymorphism, item->foo() will call DerivedItem::foo() if it is of that type otherwise it will call BaseItem::foo()

Related

Multiple inheritance and interface methods

For several graphic objects I inherit from QGraphicsLineItem, QGraphicsRectItem and so on.
class CustomLine : public QGraphicsLineItem{};
class CustomRect : public QGraphicsRectItem{};
Those objects are added to a container, a custom subclass of a QGraphicsScene "scene" that is meant for displaying and interacting with those items. this->scene->items() returns a list of QGraphicItem's: QList<QGraphicsItem* >
What I want to do is each custom object class to have the same custom interface methods, for example setModeX(). Then I could do stuff like:
Foreach (BaseItem *item, this->scene->items()){
item->setModeX(...);
}
But how do I achieve that?
If I make an interface like
class BaseItem{
public: setModeX(); [...]
private: Mode mode_;
}
and inherit
class CustomLine : public QGraphicsLineItem, BaseItem {};
So while the scene should only contain items based on BaseItem (not sure if this is really needed for this task), I first retrieve a list of objects of one of its 2 base classes, namely QGraphicsItem, and need to cast it to its other base class BaseItem to use the interface methods.
I will probably not be able to cast a CustomLine-item to BaseItem in the loop above, because it does not know about the other base class.
EDIT:
I use MinGW 4.8 32 bit (g++).
I noticed that when I start the foreach-loop, the items in my scene disappear (yet don't see the reason why)
Since scene is a QGraphicsScene, it only consists of QGraphicsItems. So you cannot directly iterate over scene as BaseItems as you show in your code. You have to iterate over each QGraphicsItem. You describe that you could downcast to your CustomLine and then upcast back to a BaseItem, but this only works if you know that all the items in the scene are lines. If scene contains other types of items, your technique would require you to iterate of each kind of item until you found a downcast that worked, and then cast it back to BaseItem.
QGraphicsItem
\ BaseItem
QGraphicsLineItem /
\ /
CustomLine
A simple solution would have been available to you if the Qt library had used virtual inheritance on QGraphicsItem. Then, you would simply need to use virtual inheritance on QGraphicsItem from BaseItem, and then down casting would have worked.
QGraphicsItem
/ \
QGraphicsLineItem BaseItem
\ /
CustomLineItem
Since Qt does not do so, you would either need to make custom changes to the Qt library, or code in your own conversion mechanism.
Assuming you are unwilling to make custom modifications to the Qt library itself, then one approach is to create a mapping between Qt's QGraphicsItem and your BaseItem. The mapping can be done within the constructor of your BaseItem, and undone from BaseItems destructor. To make undoing the mapping more efficient, you can also create a link from the BaseItem to the QGraphicsItem.
class BaseItem {
static std::unordered_map<QGraphicsItem *, BaseItem *> map;
QGraphicsItem *link_;
public:
BaseItem (QGraphicsItem *q) : link_(q) {
//...
map[q] = this;
}
virtual ~BaseItem () {
map.erase(link_);
//...
}
static BaseItem * getBaseItem (QGraphicsItem *q) {
std::unordered_map<QGraphicsItem *, BaseItem *>::iterator i;
if ((i = map.find(q)) == map.end()) return NULL;
return i->second;
}
//...
};
//...
std::unordered_map<QGraphicsItem *, BaseItem *> BaseItem::map;
In your derived classes, you would simply need to pass this to the BaseItem constructor.
class CustomLine : public QGraphicsLineItem, public BaseItem {
public:
CustomLine () : BaseItem(this) {
//...
};
//...
};
And then your loop would use the static BaseItem::getBaseItem() function to convert from a QGraphicsItem pointer to a BaseItem pointer. Thus, since there is no way to create a useable inheritance relationship between QGraphicsItem and BaseItem, their relationship is recorded in a table.
QGraphicsItem <-----------------. link
\ BaseItem <--' map
QGraphicsLineItem /
\ /
CustomLine
Should work just fine, but remember to declare the interface methods virtual in the base class, at least if you want polymorphic behavior.
Declare the functions that you want to exist in every derived class as virtual in the base class. A function that is defined as virtual in the base class can give a default implementation, but derived classes are free to override that implementation and provide their own. You can also declare that function "purely virtual" which means derived classes MUST provide an implementation for that particular function.
In either case, when calling that function on an instantiated object pointed to by a pointer of the base class, it will notice that the base class declared the function to be virtual and use a virtual table (vtable) to find which function to call (As in the base class' definition of the function, if it exists, or the derived classes version of the function).
It seems like there are some constraints on your problem that make this more of an issue than it should be. If you can't control the underlying pointers in your scene, but you know that each of those items inherits from BaseItem, then you can do a cast inside your for loop.
For instance, using the structure you have above:
Foreach (QGraphicsItem *item, this->scene){
((BaseItem*) item)->setModeX(...);
}
Of course, this is only if you can guarantee that the objects in your scene are derived from BaseItem.
CRTP to the rescue:
template <class D> class Base {
D& m_d;
public:
Base(D& derived) : m_d(d) { ... }
...
};
class CustomLine : public QGraphicsLine, Base<CustomLine> {
...
CustomLine() : Base(*this) { ... }
};

C++ multiple inheritance and access specifiers: inherit from a base class and its derived

This is an unexpected issue I've run into. I'm writing a GUI application, and I use two classes from the GUI library: a Model class and a View class. The Model contents are rendered by the View class to the screen. At some point I decided to derive the Model class because I needed extended functionality. The library's classes are meant to be derived and I found many examples. It was easy and workd perfectly.
Now there's a problem: the Model class offers methods for direct editing of the model data. I don't want these methods to be public because I wrote wrappers, and these wrappers have to be the only way to edit. I do need the inheritance because my derived MyModel overrides many virtual methods of the Model class. So I was thinking what to do. Here's a summary with all details:
There's a BasicModel class which offers methods for iteration through the model data
There's a Model class, which inherits BasicModel, and extends it by also offering methods for editing the data (I think BaseModel is abstract and has no data, and Model defines internal data structures and implements the iteration interface offered by BasicModel)
There's a MyModel class which inherits Model. It overrides many virtual methods, has extended editing mechanism and wants to hide the lower-level editing methods offered by Model
There's a View class which stores a pointer to a BasicModel object. Thus the View uses only the iteration interface, and doesn't even know about any editing interfaces.
So I want to keep MyModel's iteration interface public, so that I can pass it to my View object, but hide the editing interface offered by Model.
Solutions I thought of:
Solution 1: Inheritance can't be avoided because I have to iverride virtual methods, but the solution itself doesn't have to use inheritance: I can write a wrapper to the MyModel class, which offers access to a const reference to the encapsulated MyModel object and offers wrappers to MyModel's editing mechanism. It may be ugly because of all the wrappers, but it avoids messing with multiple inheritance and access specifiers.
Solution 2: Have MyModel inherit Model. No multiple inheritance. Now go to MyModel's class definition in MyModel.hpp and write method declarations of all Model's editing methods, under protected ir private, so that they're hidden. This works very well, but there's one little problem with maintenance: If in future versions of the library, the Model interface changes, e.g. a new editing method is added, we'll have to add it manually to the MyModel class as a private/protected method. Of course I can track the library's changes, or at least go to its online API reference and have a glance at the Model class reference page, just to make sure nothing's changes, or update my code if necessary, before a production/stable version of my application is released.
Solution 3: Use multiple inheritance, and then I have no idea what's supposed to happen. Is it safe or not. Is the behavior compiler dependent or not. This is the idea: MyModel inherits from Model and from basicModel: public inheritance from BasicModel (for the iteration interface) and protected/private inheritance from Model (in order to hide Model's editing interface).
Notes:
Note 1: My high-level editing mechanism uses Model's lower-level editing methods.
Note 2: The virtual methods MyModel overrides, some of them are defined by BasicModel (thus inherited by Model too) and some don't exist in BasicModel and are defined by Model (e.g. methods related to drag-n-drop).
Note 3: The GUI library I use is gtkmm, the C++ binding of GTK+, and the classes I'm talking about are Gtk::TreeModel, Gtk::TreeStore, Gtk::TreeView and my own MyModel class, which derives from Gtk::TreeStore. I ignored these names because the question is a general OO planning question, but I'm mentioning the real classes here so that people who are familiar them will understand the problem much more easily.
I'm not sure what would be the best design here. Definitely solution 3 is the one with the lowest maintenance cost. It's actually zero, because the inheritance access specifiers just do all the work automatically. The question is, does solution 3 always work as expected, e.g. for an iteration method, will compilers make it public (because of public inheritance from BasicModel) or private (because of private inheritance from Model, which is derived from BasicModel). I never used multiple inheritance like this...
Pseudo-Code
This is more or less how the library works:
namespace GUI
{
class BasicModel
{
public:
/* iteration interface for observing the model */
iterator get_iter();
// but no data here, it's just an interface which calls protected virtual methods
// which are implemented by deriving classes, e.g. Model
protected:
virtual iterator get_iter_vfunc() = 0;
virtual void handle_signal();
};
class Model : public BasicModel
{
/* inherits public iteration interface*/
/* implements observation virtual methods from BasicModel*/
virtual iterator get_iter_vfunc() { /*...*/ }
/* has private data structures for the model data */
std::vector<Row> data;
/* has public editing interface, e.g. insert_row(), erase(), append()
/* has protected drag-n-drop related virtual methods*/
virtual void handle_drop();
};
}
My code:
class MyModel : public GUI::Model
{
/* implements virtual methods from BasicModel, e.g. default signal handlers*/
virtual void handle_signal() { /*...*/ }
/* implements drag-n-drop virtual methods from Model*/
virtual void handle_drop() { *...* }
/* inherits public iteration interface*/
/* inherits public editing interface (***which I want to hide***)
/* implements its own editing mechanism*/
void high_level_edit (int param);
};
Experiment with GCC
I tried the following code, compiled with warnings off (otherwise GCC complains):
#include <iostream>
class Base
{
public:
void func ()
{
std::cout << "Base::func() called" << std::endl;
func_vfunc ();
}
protected:
virtual void func_vfunc ()
{
std::cout << "Base::func_vfunc() called" << std::endl;
}
};
class Derived : public Base
{
protected:
virtual void func_vfunc ()
{
std::cout << "Derived::func_vfunc() called" << std::endl;
}
};
class MyClass : public Base, private Derived
{
};
int main (int argc, char* argv[])
{
Base base;
Derived derived;
MyClass myclass;
base.func ();
derived.func ();
myclass.func ();
return 0;
}
For some reason GCC insists the call myclass.func() is ambigous, but one of the func()s us supposed to be private because of the private inheritance, so I don't understand why it cannot compile. Bottom line, assuming it's not a bug but just me not understanding how things work - the suggested solution of multiple inheritance is impossible. The only way to fix this problem, if I'm not mistaken, is virtual inheritance, but I can't use it because the classes I use are library classes and they don't use virtual inheritance. And even then, since I use private and public inheritance together, it may not solve the problem and still be an ambigous call.
EDIT: I tried making Derived and MyClass derive virtually from Base, and it fully solves the problem. But in my case, I can't change library classes, so it's not an option.
If I understand your problem correctly, you should probably use a mix of inheritance (MyModel derives from BaseModel) and composition (MyModel contains a private instance of Model).
Then in MyModel use your own implementation of the base virtual methods, and for the ones you don't want to reimplement just make them a proxy to the corresponding Model methods.
Anyway, IMHO you should avoid multiple inheritance if you can. It can get pretty hairy over time otherwise.
EDIT: Now that I can see the code, I'll give it another shot.
What you need to do is reimplement whatever you need in a class MyModelImpl (derives from Model) which will be hidden inside a proxy class MyModel (derives from BaseModel). My first idea was very similar except I didn't understood that you needed to reimplement some parts of Model.
Something along the lines of:
class MyModel : public BaseModel {
public:
void high_level_edit(int param) { m_impl.high_level_edit(param); }
protected:
virtual iterator get_iter_vfunc() { return m_impl.get_iter_vfunc(); }
virtual void handle_signal() { m_impl.handle_signal(); }
private:
class MyModelImpl : public Model {
public:
void high_level_edit(int param);
// reimplement whatever you need (methods present in BaseModel,
// you need to call them from MyModel proxies)
virtual iterator get_iter_vfunc() { /*...*/ }
protected:
// reimplement whatever you need (methods present only in Model,
// you don't need to call them from MyModel proxies)
virtual void handle_drop();
};
MyModelImpl m_impl;
};
I believe that should work correctly since there is no actual state (data) in BaseModel, unless there is something I misunderstood again...
You can do something like
class MyModel : protected Model
{
public:
using Model::iterator;
//it will make iterator public in MyModel
}
if I understand the case correctly, and provided Model doesn't inherit privately from iterable class, which must be the case here, I guess. Pardon me if I said something stupid. I'm not a very experienced coder.

Avoid overriding members when inheriting

I need to use C++. C++11 would be interesting, but I'd prefer without. I have the following class structure.
class Wheel { /*...*/ };
class MtbWheel : public Wheel { /*...*/ };
class Bike { Wheel front_wheel; };
class Mountainbike : public Bike { MtbWheel front_wheel; };
Now, this completely works: The Mountainbike overrides front_wheel, and thus can use an MtbWheel. Softwaretechnically, I am not happy, though.
What I would prefer is disallowing to override front_wheel, or at least restrict overwriting by classes that do not inherit class Wheel.
Instead of overriding front_wheel, I'd like only to "add" properties to it.
EDIT: Is there a solution without virtual functions, but with templates instead?
Your front_wheel member in Mountainbike class does not override front_wheel, it hides it. Mountainbike class actually has two front_wheel members, but the one from the Bike class is hidden by the one declared in Mountainbike. Meaning that if Bike accesses front_wheel, it will access an object of type Wheel, while when Mountainbike accesses front_wheel, it will access an object of type MtbWheel - but these two wheel objects don't know of each other!
Better OO design would be to make front_wheel e.g. a pointer in Bike (or even better a smart pointer), and initialize it in the constructor of Mountainbike to hold an object of a class derived from Wheel which fits best to Mountainbike. That way, when accessing front_wheel, one way or the other virtual functions come into play of course.
An alternative solution, as per Steve Jessop's suggestion in the comments below, making use of templates instead of using polymorphism, would be:
class Wheel { /*...*/ };
class MtbWheel : public Wheel { /*...*/ };
template <typename WheelType>
class Bike { WheelType front_wheel; };
class Mountainbike : public Bike<MtbWheel> { /* ... */ };
That way, no virtual functions are involved when operating on front_wheel. There are some points to consider with such a solution, however:
For each different WheelType you use Bike with, separate code will be created; if you have many different such types, this might result in code bloat.
If you have more than one class derived from Bike with different WheelType parameters, they do not have the same base class (see Steve Jessop's comment, and point 1), and therefore also can't be accessed polymorphically.
You can not enforce an explicit interface on the WheelType being passed as template parameter to Bike; only the implicit interface is defined by the methods and members used from Bike. That should be no problem however, since the compiler can still verify that implicit interface.
You're not overriding anything. There is still a Wheel front_wheel; in your derived class. You can access it through m.Bike::front_wheel, or something like that. If you want derived classes to provide their own instantiations of front_wheel, then you will need to only provide a virtual accessor in the base class and let derived classes create their own.
The variable front_wheel is not overriden - it is just hidden. The member variable Wheel front_wheel is still in the Mountainbike class. So actually there are two variables named front_wheel in Mountainbike. But to access the hidden variable in Mountainbike you would need to say it explicitly: Bike::front_wheel.
A better way of doing what you want is to create an interface class with no data:
class Bike {
public:
virtual Wheel const &getFronWheel() const = 0;
virtual ~Bike() {}
};
and then derive any specific bike from that:
class RegularBike: public Bike {
public:
virtual Wheel const &getFronWheel() const { return wheel; }
private:
Wheel wheel;
}
class MtbBike: public Bike {
public:
virtual MtbWheel const &getFronWheel() const { return wheel; }
private:
MtbWheel wheel;
}
Edit: Without using virtuality, but templates instead:
template<typename WheelType>
class Bike {
public:
/* Common methods for any bike...*/
protected: // or private
WheelType wheel;
};
Then you can extend the Bike as you wish:
class RegularBike: public Bike<Wheel> {
/* Special methods for regular bike...*/
};
class MtbBike: public Bike<MtbWheel> {
/* Special methods for Mtb bike...*/
};
You can create a interface of IWheel instead of Class Wheel.
Create OverRide method in MtbWheel class. So that whoever wants to override this method can override this method else use the default method which we have implemented in MtbWheel class. By using this you can add properties of it.
The solution is to not do that. Writing a derived class requires careful study of the base class, followed by careful design. Magic cookies are no substitute for knowledge and thought. And, yes, I've made my share of this kind of mistake, and kicked myself for being careless.

Derived class from a templated base class

I am quite new to real use of templates, so I have the following design question.
I am designing classes Bunch2d and Bunch4d that derive from a abstract base class Bunch:
class Bunch {virtual void create()=0;};
class Bunch2d : public Bunch {void create();};
class Bunch4d : public Bunch {void create();};
The class Bunch will contain a container, a deque or a vector (see this question: Choice of the most performant container (array)) of Particle's:
typedef Blitz::TinyVector<double,DIMENSIONS> Particle;
You therefore see my question: Bunch has to contain this container, because the "base" operations on my bunch are "dimension independant" (such a "size of the container", "clear container", etc.), so I think that the container belongs to the base class ("Bunch 'has a' container).
But this container has to know the dimensions (2 or 4) of the derived class.
So my idea would be to use a templated base class to give the typedef the correct dimension of the container:
enum Dimensions {TwoDimensions = 2, FourDimensions = 4, SixDimensions = 6};
template<Dimensions D> class Bunch
{
protected:
typedef Blitz::TinyVector<double,D> Particle;
std::deque<Particle> particles_store;
public:
virtual void create() = 0;
virtual ~Bunch();
};
class Bunch2d : public Bunch<TwoDimensions>
{
public:
~Bunch2d();
void create();
};
class Bunch4d : public Bunch<FourDimensions>
{
public:
~Bunch4d();
void create();
};
Can you give me your opinion on this design ? Would it be correct use of templates ? What about the validity of the OO concepts ? With a templated base class ?
Thanks for you help/answer/opinion.
There is one single note: different template instances (ie template classes with different types in the parameters) are of different types, and therefore are NOT a single base class.
If you need polymorphism, you will need to add a layer in your design:
class Bunch
{
public:
virtual void create() = 0;
virtual ~Bunch();
};
template <Dimensions D>
class TBunch: public Bunch
{
private:
typedef Blitz::TinyVector<double,D> Particle;
std::deque<Particle> mParticles;
};
class Bunch2d : public TBunch<TwoDimensions>
{
public:
~Bunch2d();
void create();
};
On another note: protected should be banned for attributes.
The issue is one of coupling, since protected exposes the attributes / methods to an unknown number of classes, it's no different than public in that it's impossible to reliably state how many methods will be affected by a change of implementation.
For methods, it's acceptable, because methods can be kept backward compatible (sometimes at the cost of some tricks / etc... but still).
For attributes, it's just unacceptable because an attribute is an implementation detail, not an interface, and a change cannot be made backward compatible.
Therefore I urge you not to EVER use protected for an attribute. In this particular case, it would be a good idea to factor the accesses to mParticles in the template class, without exposing the underlying implementation.
Small hint: if you cannot switch between deque and vector without breaking something beyond the class that holds them, then you have a design issue.
You'd then loose the ability to have a pointer of Bunch class pointing to either Bunch2d or Bunch4d objects at runtime, and manipulate those objects polymorphically through that pointer. If it's important to you not to loose that, don't make the base class templated. Otherwise there is no point in having virtual functions and abstract base class here at all, so then I'd recommend going just with the template.
For a start, Bunch<TwoDimensions> and Bunch<FourDimensions> are completely unrelated classes, so far as inheritance is concerned. Therefore, Bunch2d and Bunch4d have no common base class!
If this is going to be a problem for you, you'll have to do away with the templating, and have DIMENSIONS parameterised at run-time.

Modeling "optional" inheritance

I'm having trouble deciding on a way to model this type of relationship...
All bosses can do certain things and have certain things (velocities, health, etc.) so these are part of the "main" abstract boss class.
class Boss // An abstract base class
{
//Stuff that all Bosses can do/have and pure virtual functions
};
Now I want to specify a few more pure virtual functions and members for bosses that can shoot. I'm wondering how I should model this? I've considered deriving a ShootingBoss Class from the Boss class, but specific bosses are classes in themselves (with Boss just being an abstract base class that they are derived from.) Thus if ShootingBoss is derived from Boss, and a specific boss derives from ShootingBoss, that boss won't be able to access the protected data in the Boss class.
Boss(ABC) -> ShootingBoss(ABC) -> SomeSpecificBoss(can't access protected data from Boss?)
Basically, I'm wondering what the recommended way to model this is. Any help is appreciated. If more information is needed, I'd be happy to offer.
I think you need to look into Mixin classes.
For example, you could create the following classes:
class Boss {
// Here you will include all (pure virtual) methods which are common
// to all bosses, and all bosses MUST implement.
};
class Shooter {
// This is a mixin class which defines shooting capabilities
// Here you will include all (pure virtual) methods which are common
// to all shooters, and all shooters MUST implement.
};
class ShootingBoss : public Boss, public Shooter
{
// A boss who shoots!
// This is where you implement the correct behaviour.
};
Mixins require multiple inheritance to be used, and there are many pitfalls and complexities to doing so. I suggest you look at answers to questions like this one to ensure that you avoid these pitfalls.
Why not start using interfaces? So, rather than simply uber base class, you spread out your things into capabilities.
struct IBoss : public IObject
{
}
struct ICanShoot : public IObject
{
}
Generally to implement this you derive your interfaces from another interface which allows you to query for an interface.
struct IObject
{
int getId(); // returns a unique ID for this interface.
int addRef();
int release();
bool queryInterface(int id, void** pp);
}
That way, you implement your Boss more easily:
class Boss : public IBoss, public ICanShoot
{
};
It might be overkill for some, but if your class heirachy is all screwed up, this is the best way out of the mess.
Have a look at M$'s IUnknown interface.
There are two different ways of doing this:
1) Mixin classes (already explained)
2) Role playing classes.
Role playing has it's advantages and disadvantages. Roles, that object can play (boss, shooter, whatever) are implemented using containment. They must be derived from the common base interface class, which will have to be downcasted dynamicaly (argh..). Caller will ask object of your class for the role pointer (this is where downcast will come in) and if object can play the role (returned non-NULL pointer) client will call appropriate function of the role.
Main advantage of role playing approach (appart from avoiding multiple inheritance) - it is dynamic. Object can accept new roles at runtime, as opposed to mixin that has to be defined at compile time.
Also it is scalable. In multiple inheritance (mixin) approach if you decide to expand your hierarchy with "Protector" and say that boss can be simple Boss, ShootingBoss, ProtectingBoss, ShootingProtectingBoss, and later expand it ufrther with Сoward (Boss, ShootingBoss, ProtectingBoss, ShootingProtectingBoss, CowardBoss, CowardShootingBoss, CowardProtectingBoss, CowardShootingProtectingBoss) - you see your hierarchy explodes. This is when you need to switch to role playing model, where object will simply have to accept new role Coward. But until you are sure that you need it - stick with mixin classes.
Below is hierarchy sketch for role playing lcases:
class IRole
{
// some very basic common interface here
public:
virtual ~IRole() {}
};
class IBoss : public IRole
{
};
class IShooter : public IRole
{
};
class IProtector : public IRole
{
};
class MultifunctionalPerson
{
public:
bool AcceptRole(IRole* pRole); // pass some concrete role here
IRole* GetRole(int roleID);
};
// your clinet will be using it like that
MultifunctionalPerson& clPerson = ... (coming from somewhere);
// dynamic_cast below may be replaced with static_cast if you are sure
// that role at PROTECTOR_ROLE location is guaranteed to be of IProtector type or NULL
IProtector* pProtector = dynamic_cast<IProtector*>(clPerson.GetRole(PROTECTOR_ROLE));
if( 0 != pProtector )
{
pProtector->DoSomething();
}