conectionist
conectionist

Reputation: 2914

Diamond inheritance code in C++ not working as expected

I'm trying to understand the solution to the diamond problem (multiple inheritance) in C++.

I've written this code to better understand the solution but it doesn't behave as expected.

#include <stdio.h>

class A
{
public:
    void Print()
    {
        printf("A\n");
    }
};

class B : virtual public A
{
public:
    void Print()
    {
        printf("B\n");
    }
};

class C : virtual public A
{
public:
    void Print()
    {
        printf("C\n");
    }
};

class D : public B, public C
{
};

int main()
{
    D d;
    d.Print();
}

Visual studio 2008 express edition yells out : error C2385: ambiguous access of 'Print' 1> could be the 'Print' in base 'B' 1> or could be the 'Print' in base 'C' error C3861: 'Print': identifier not found

Can anyone please tell me what I'm missing here?

Upvotes: 1

Views: 269

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153820

Which version of Print() should d.Print() call? There are two choices. You can choose, though:

d.A::Print(); // this one isn't part of the overload set search without qualification
d.B::Print();
d.C::Print();

Note that making A::Print() a virtual function won't help as there is no unique final overriding function. You'd need to explicitly override Print() in D.

Upvotes: 1

Related Questions