开发者

Extending the method pool of a concrete class which is derived by an interface

I had created an interface to abstract a part of the source for a later extension. But what if I want to exten开发者_高级运维d 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜