tags:

views:

72

answers:

1

Hello, I had created an interface to abstract a part of the source for a later extension. But what if I want to extend the derived classes with some special methods? So I have the interface here:

class virtualFoo
{
public:
 virtual ~virtualFoo() { }

 virtual void create() = 0;
 virtual void initialize() = 0;
};

and one derived class with an extra method:

class concreteFoo : public virtualFoo
{
public:
 concreteFoo() { }
 ~concreteFoo() { }

 virtual void create() { }
 virtual void initialize() { }

 void ownMethod() { }
};

So I try to create an Instance of concreteFoo and try to call ownMethod like this:

void main()
{
 virtualFoo* ptr = new concreteFoo();
 concreteFoo* ptr2 = dynamic_cast<concreteFoo*>(ptr);

 if(NULL != ptr2)
  ptr2->ownMethod();
}

It works but is not really the elegant way. If I would try to use ptr->ownMethod(); directly the compiler complains that this method is not part of virtualFoo. Is there a chance to do this without using dynamic_cast?

Thanks in advance!

+1  A: 

This is exactly what dynamic_cast is for. However, you can usually avoid using it by changing your design. Since you gave an abstract example, it's hard to judge whether you should be doing things differently.

Cogwheel - Matthew Orlando
Thank you!My real interface is intended to abstract input devices, like mouse or keyboard. The idea was to create an interface which abstracts methods which are definitively used by both devices, like buttonDown() or buttonUp(). Methods which only make sense for one specific device are only in the derived class, not in the interface. So a mouse would have its very own getPosX(), something which should not be in the interface, as a device like keyboard would never need this. So I don't want to have this in the interface - also to avoid method calls which are not part of the input device.
CelGene
`dynamic_cast` is most useful when you want to store base class pointers in a container. Another common use is interfacing with libraries/APIs that allow you to store some of your own data inside one of its structures (like cbWndExtra in windows programming). But most of the time, code you write that deals with a base class pointer/reference shouldn't need to do anything with derived class-specific interfaces.
Cogwheel - Matthew Orlando