1

I need to query up and query down the interface pointer in my program,

I have interface defined

struct Iinterface1
{
    methods X1()
}

struct Iinterface2 : Iinterface1
{

     methods X2()
}

queryInterface( *interface)
{
  returns the pointer to one of above interface
}

i can query and get the pointer to interface using function queryInterface()

since interface2 came later, i need to support both method1 and method2 in my program, so i can not have interface pointer to interface2 and execute method x1 and method x2. what i am looking is how to upgrade or change interface pointer during execution. so i would query and get pointer to interface1 and execute method x1 and later when i want to execute method x2 , i need to query up my pointer to interface2 so i can execute method x2. makes sense? appreciate any help with example.

James M
  • 18,506
  • 3
  • 48
  • 56
NxC
  • 320
  • 1
  • 2
  • 16
  • this doesn't look much like COM interfaces, it'd help if you posted your actual code – M.M Aug 19 '14 at 10:29

1 Answers1

1

Assuming Interface1 has a virtual method, then if you have a pointer to Iinterface1, you can test to see if it is an Iinterface2 with a dynamic cast:

const Iinterface2 * is_Iinterface2 (const Iinterface1 *p) {
    return dynamic_cast<const Iinterface2 *>(p);
}

If the result is NULL, then p did not come from an object that had derived from Interface2.

C++ does not have a way to dynamic query to determine if a class has particular method.

jxh
  • 69,070
  • 8
  • 110
  • 193
  • If the base has a virtual function. – Neil Kirk Aug 15 '14 at 23:49
  • Thanks @jxh and Neil , uhm i am not sure if this works for my part of code, need to modify lot of part, i am new to COM and its all i see stars in the sky :( – NxC Aug 16 '14 at 00:12
  • You have to implement COM yourself (or find a library that does it for you). There is no direct C++ support to query an interface the way COM specifies it. – jxh Aug 16 '14 at 00:18
  • In COM, `dynamic_cast` on an interface pointer actually calls QueryInterface and results in the pointer being `AddRef`'d. (COM is meant to be a language-agnostic generalization of C++'s object model) . I guess it is a matter of opinion whether it is clearer to use `dynamic_cast` or to explicitly call `QueryInterface`. NB- this is what happens in C++Builder; reading [other comments](http://stackoverflow.com/questions/1460795/dynamic-cast-of-a-com-object-to-a-com-interface-doesnt-bump-the-reference-count) suggests that perhaps MSVC causes UB when you dynamic_cast a COM interface pointer. – M.M Aug 19 '14 at 10:33