Two different pure virtuals with same name

Is there any way to define C?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
struct A
{
    virtual ~A(){}
    virtual void f() = 0;
};
 
struct B
{
    virtual ~B(){}
    virtual int f() = 0;
};
 
struct C : virtual A, virtual B
{
    virtual ~C(){}
    virtual void A::f() //error
    {
        std::cout << "C::A::f" << std::endl;
    }
    virtual int B::f() //error
    {
        std::cout << "C::B::f" << std::endl;
        return 7;
    }
};
the problem here is that you are trying to implement a definition for functions A::f() and B::f() but these are pure virtual functions and therefore a class that inherit from struct A and struct B has to provide its own implementation for those two functions. so on line #16 and line#20, you can not provide an implementation for pure virtual functions (line# 4 and line #10).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>

struct A
{
    virtual ~A(){}
    virtual void f() = 0;
};

struct B
{
    virtual ~B(){}
    virtual int f() = 0;
};

struct A_1 : virtual A // intermediate class to disambiguate f()
{
    virtual void f() override { A_f() ; } // map f() to A_f()
    protected : virtual void A_f() = 0 ;
};

struct B_1 : virtual B // intermediate class to disambiguate f()
{
    virtual int f() override { return B_f() ; } // map f() to B_f()
    protected : virtual int B_f() = 0 ;
};

struct C : virtual A_1, virtual B_1
{

    // do not override f()

    protected:

        // override A_f() and B_f()
        
        virtual void A_f() override
        {
            std::cout << "C::A::f" << std::endl;
        }

        virtual int B_f() override
        {
            std::cout << "C::B::f" << std::endl;
            return 7;
        }
};

int main()
{
    C c ;
    A& a = c ; a.f() ; // C::A::f (C::A_f)
    B& b = c ; b.f() ; // C::B::f (C::B_f)

    // c.f() ; // *** error: ambiguous
}
Last edited on
Ah, I knew there had to be some intermediate magic.

I can still do c.A_1::f and c.B_1::f too, which is nice. Thanks!
Last edited on
Topic archived. No new replies allowed.