Re: C++ Design question
<denis_browne@hotmail.com> wrote in message
news:1168767819.334570.242450@v45g2000cwv.googlegroups.com...
Hi All,
I'm making a class which derives(implements) from 5 interfaces:
class myClass: public base1, public base2, public base3,.......
I want to be able to ask from any interface about a pointer to another
interface
What I mean is:
myClass _myImpObj;
base1 *b1 = &_myImpObj;
base *b2 = b1->QueryInterafce("b2");
base *b3 = b2->QueryInterafce("b3");
base *b1N = b3->QueryInterface("b1");
Its is very simialir to COM mechanism.Anyone knows how to implement it?
The dynamic_cast<>() operator is what you are looking for. Note that there
is no way to overload on the return type, so you have to use some variant of
the scheme used by COM - if the returned pointer is not 0, we "know" that it
is really of the required type and a reinterpret_cast<>() will give the
correct result.
Caller:
base1* pBase1 = new MyClass(...);
// Many lines of code later
void* p = pBase1->QueryInterface( "b2" );
base2* pBase2 = 0;
if ( p )
pBase2 = reinterpret_cast< base2* >( p );
else { /* handle error here */ }
Callee:
void* myClass::QueryInterface( const std::string& type )
{
if ( type == "b1" )
return dynamic_cast< base1* >( this );
else /* handle other cases here */
return 0; // failure! */
}
HTH
Daniel Pfeffer
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]