Re: strange ambiguity in the derived class
On 11.05.2010 08:23, * vj:
Hello,
Trying to compile the example at the end of this post, I am getting
next errors:
[packman@localhost test]$ g++ p.cpp
p.cpp: In member function ?void D::foo1()?:
p.cpp:39: error: request for member ?boo? is ambiguous
p.cpp:16: error: candidates are: const int& B::boo() const
p.cpp:6: error: int& A::boo()
p.cpp: In member function ?void D::foo2() const?:
p.cpp:41: error: request for member ?boo? is ambiguous
p.cpp:16: error: candidates are: const int& B::boo() const
p.cpp:6: error: int& A::boo()
Can someone explain why the example doesn't compile?
The signatures of A:boo() and B:boo() methods are different (one is
const, other isn't).
How to change the example, to make it compile?
Thank in advance.
And the example is here:
#include<iostream>
class A
{
public:
virtual ~A(){}
int& boo()
{ return vboo(); }
private:
virtual int& vboo() = 0;
};
class B
{
public:
virtual ~B(){}
const int& boo() const
{ return vboo(); }
private:
virtual const int& vboo() const = 0;
};
class C : public A, public B
{
public:
C():p(5){}
virtual ~C(){}
private:
virtual const int& vboo() const
{ return p; }
virtual int& vboo()
{ return p; }
int p;
};
class D
{
public:
void foo1()
{ std::cout<<"D::foo1() ++c.boo()="<<++c.boo()<<std::endl; }
void foo2() const
{ std::cout<<"D::foo1() c.boo()const="<<c.boo()<<std::endl; }
private:
C c;
};
int main()
{
D d;
d.foo1();
d.foo2();
}
The error is apparently caused by the possible boo's coming from different
classes, at some point before their signatures are considered.
I think you can find the relevant sections of the standard yourself, but as a
practical matter, put
using A::boo;
using B::boo;
in the public section of your C class.
Then (apparently) the compiler is happy to also consider the signatures, and
discovers that one of them is a better match.
Cheers & hth.,
- Alf
(blog at <url: http://alfps.wordpress.com>)