I tried the following code using several GCCs and got problems when I run the code which is compiled using O1 with gcc4.7.1 and onward.

#include <stdexcept>
#include <iostream>

struct Interface_1
{
    virtual void setA() = 0;
};

struct Interface_2
{
    virtual void setB() = 0;
};

struct Master: Interface_1, Interface_2
{
    void setA()
    {
        throw std::runtime_error("I was thrown");
    }
    void setB()
    {
        throw std::runtime_error("I was thrown");
    }
};

int main()
{
    Master m;
    Interface_2& i2 = m;
    try
    {
        i2.setB();
    }
    catch (const std::runtime_error& e)
    {
        std::cout << "Caught exception e=" << e.what() << std::endl;
    }
    catch (...)
    {
        std::cout << "Did not catch exception" << std::endl;
    }

    std::cout << "Done running" << std::endl;
}

In the code above I am a reference from interface Interface_2 to refer to an object from Master class, and this will result into a crash

terminate called after throwing an instance of 'std::runtime_error'
  what():  I was thrown
Abort (core dumped)

But it works if I use a reference from Interface_1:

int main()
{
    Master m;
    Interface_1& i1 = m;
    try
    {
        i1.setA();
    }
    catch (const Exception& e)
    {
        std::cout << "Caught exception e=" << e.what() << std::endl;
    }
    catch (...)
    {
        std::cout << "Did not catchexception" << std::endl;
    }

    std::cout << "Done running" << std::endl;
}

I just get what is expected:

Caught exception e=I was thrown
Done running

It seems that the first interface that I inherit from can just be used to refer to a object from Master class. I also made the inheritance from the first interface as follows:

class Master: public virtual Interface_1, public Interface_2

Then references from Interface_2 just turned out to be fine. Instead, I got problem with references from Interface_1.

I have tried this with g++ up to 4.9, and I don't know if it is working in 5.x versions. Unfortunately I cannot just go and change the compiler's version. I should stick with 4.8 due to limitation and restriction. Therefore I wonder if you guys know any alternate/smart way to tackle this problem.

0

There are 0 best solutions below