CelGene
CelGene

Reputation: 1

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 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!

Upvotes: 0

Views: 145

Answers (1)

Cogwheel
Cogwheel

Reputation: 23217

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.

Upvotes: 1

Related Questions