Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Have code as 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 there is a default implementation of F() in the base classes.

Thanks to Jan Herrmann and Spook. Is the below a simpler solution if we have to use some extra 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;
}
like image 863
user1899020 Avatar asked Feb 07 '13 15:02

user1899020


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'm remembing right the ISO committee thought about this problem and discussed a change of the language. But then ... somebody found this nice way to solve this problem :-)

Your second solution is better in case your are able to change your class hierarchy. You may have a lock at http://www.gotw.ca/publications/mill18.htm for a description why it is better.

like image 171
Jan Herrmann Avatar answered Nov 09 '22 09:11

Jan Herrmann


Try this:

#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;
}

Take into consideration though, that you won't be able to call F from C's instance (ambiguous call).

Also, F has to be abstract in A and B, otherwise you'll get compilation error:

Error 1 error C3240: 'F' : must be a non-overloaded abstract member function of 'A'
like image 38
Spook Avatar answered Nov 09 '22 09:11

Spook