Question

msft compilers for C++ support explicit overriding (see http://msdn.microsoft.com/en-us/library/ksek8777.aspx)

// could be declared __interface I1, making the public scope and pure virtual implied
// I use the more expressive form here for clarity
class I1
{
public:
  virtual void foo() = 0;
};

class I2
{
public:
  virtual void foo() = 0;
};

class C : public I1, public I2
{
public:
  virtual void I1::foo() { cout << "I1::foo\n"; }
  virtual void I2::foo() { cout << "I2::foo\n"; }
};

int main()
{
  C c;
  static_cast<I1*>(&c)->foo();
  static_cast<I2*>(&c)->foo();

  cin.get();
}

But gcc doesn't like this. A simple "explicit overrides" online search yields information about the new keyword override. That isn't necessarily related to what I am looking for. Is this feature supported in some other way in c++11 (per spec) or at least in some way in gcc?

Note: an acceptable answer can be a hack - as long as it is in the same spirit of the question and not a new design to solve a different problem.

Was it helpful?

Solution

I believe the only way is via intermediate classes which implement the functionality:

class Impl1 : public I1 {
public:
    void foo() { cout << "I1::foo\n"; }
};

class Impl2 : public I2 {
public:
    void foo() { cout << "I2::foo\n"; }
};

class C : public Impl1, public Impl2
{
};

Granted, this makes it rather more complicated once these functions need to access members of C – they can’t, the members need to be passed around in a convoluted manner.

By the way, no need for pointers; you can use references:

int main()
{
    C c;
    static_cast<I1&>(c).foo();
    static_cast<I2&>(c).foo();
}

(Or use explicit qualification which avoids the virtual dispatch altogether:)

c.Impl1::foo();
c.Impl2::foo();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top