Possible Duplicate:
Inherit interfaces which share a method name
I have two base classes I1
and I2
with pure virtual functions void R() = 0;
. I want the derived class IImpl
to inherit from I1
and I2
and to have distinct implementations for I1::R()
and I2::R()
.
The code below compiles and works in MS VS 2005 and 2010. I compile with Language Extension disabled and on warning level 4. There are no warnings and no errors.
I tried the same code in gcc 4.2. It does not compile. GCC reports an error:
error: cannot define member function 'I1::R' within 'IImpl'
My questions are:
Thanks!
#include <stdio.h>
class I1
{
public:
virtual void R() = 0;
virtual ~I1(){}
};
class I2
{
public:
virtual void R() = 0;
virtual ~I2(){}
};
class IImpl: public I1, public I2
{
public:
virtual void I1::R()
{
printf("I1::R()\r\n");
}
virtual void I2::R()
{
printf("I2::R()\r\n");
}
};
int main(int argc, char* argv[])
{
IImpl impl;
I1 *p1 = &impl;
I2 *p2 = &impl;
p1->R();
p2->R();
return 0;
}
This code is non-standard, according to 8.3/1
A declarator-id shall not be qualified except for the definition of a member function (9.3) or static data member (9.4) outside of its class,...
so you can't qualify member function names when declaring/defining them inside the class. That's why it isn't compiled by gcc.
MSVC seems to have a non-standard extension allowing such code. I guess it was done for Managed Extensions for C++, that's exactly how explicit interface implementations were done there and although it was deprecated long ago seems that syntax is still supported.
A correct way to implent it is decribed at the link provided by Björn Pollex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With