How to implement virtual functions with the same name in multiple inheritance

Enter the code below

// A has a virtual function F().
class A
{
public:
    virtual void F() {};
};

// The same for B.
class B
{
public:
    virtual void F() {};
};

// C inherits A and B.
class C : public A, public B
{
public:
    // How to implement the 2 virtual functions with the same name but from
    // different base classes.
    virtual F() {...}
};

Note that in base classes there is a default F () implementation.

Thanks to Jan Herrmann and Spauk. Is the below a simpler solution if we need to use additional helpers?

#include <iostream>

// A has a virtual function F().
class A
{
private:
    virtual void A_F() {}

public:
    void F() {return A_F();};
};

// The same for B.
class B
{
private:
    virtual void B_F() {}

public:
    void F() {return B_F();};
};

// C inherits A and B.
class C : public A, public B
{
private:
    virtual void A_F() {std::cout << "for A\n";}
    virtual void B_F() {std::cout << "for B\n";}

};

int main()
{
    C c;
    c.A::F();
    c.B::F();
    return 0;
}
+5
source share
2 answers
class C_a 
  : public A
{
  virtual void F_A() = 0;
  virtual void F() { this->F_A() };
};

class C_b
  : public B
{
  virtual void F_B() = 0;
  virtual void F() { this->F_B() };
};

class C
  : public C_a
  , public C_b
{
  void F_A() { ... }
  void F_B() { ... }
};

If I return correctly, the ISO committee thought about this issue and discussed a language change. But then ... someone found this good way to solve this problem :-)

The second solution is better if you can change the class hierarchy. You may have a http://www.gotw.ca/publications/mill18.htm lock to describe why this is better.

+4
source

:

#include <cstdio>

class A
{
public:
    virtual void F() = 0;
};

class B
{
public:
    virtual void F() = 0;
};

class C : public A, public B
{
    void A::F()
    {
        printf("A::F called!\n");
    }

    void B::F()
    {
        printf("B::F called!\n");
    }
};

int main(int argc, char * argv[])
{
    C c;
    ((A*)(&c))->F();
    ((B*)(&c))->F();

    getchar();

    return 0;
}

, F C ( ).

, F B, :

Error 1 error C3240: 'F' : must be a non-overloaded abstract member function of 'A'
+2

All Articles