-4

I need to cast interface pointer dynamically but my interfaces dont have any virtual method, basically i do not control the code of interfaces and i want to user same pointer to use methods from both interfaces, if i cast dynamically then since interfaces are not polymorphic type, it does not allow, what options do i have?

Code looks like this

Interface 2 : interface 1
{
     foo();
}
Interface 3: Interface 2
{
     koo();
}

some class
{
     Interface 2 *ptr;
     ptr->foo();

Now i want to user same pointer to access interface 3 methods

dynamicaly cast the interface pointer

     Interface3 *ptr = dynamic_cast<Interface3 *>(ptr);
     ptr->koo();
}

It tells me cant do since Interface3 is not polymorphic, now i do not have control over the interfaces, yet i want to use same pointer to both the interface, how can i achieve this?

NxC
  • 320
  • 1
  • 2
  • 16

1 Answers1

3

Given the almost-code you wrote, where you know ptr points to an Interface2, if you have some way of knowing for sure that ptr in fact points to an Interface3, you can just use a static cast:

Interface3 *ptr3 = static_cast<Interface3 *>(ptr);
ptr3->koo();

However, if you don't know for sure that ptr really points to an Interface3, there's nothing the compiler or runtime can do to tell you.

Maybe there's some other field of Interface1 or Interface2 that you can look at to know if it's really an Interface3, but that depends on details of the library that you chose not to include in your question.

If you want more help, you'll have to provide more details in your question.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848