Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct implementations for pure virtual functions with same name [duplicate]

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:

  1. Why that code works in MS VS and why it does not work in gcc?
  2. Is the code a standard C++?
  3. What is the correct way to implement it, so it is a standard C++ and compiles on VS and gcc?

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;
}
like image 644
user1017802 Avatar asked Oct 28 '11 06:10

user1017802


1 Answers

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.

like image 147
Konstantin Oznobihin Avatar answered Oct 30 '22 08:10

Konstantin Oznobihin