multiple inheritance question

Should I perceive it as C++ flaw or there is some good reason why it is like that:

g++ -o XXX XXX.cpp
XXX.cpp: In function 'int main(int, char**)':
XXX.cpp:26: error: request for member 'operator[]' is ambiguous
XXX.cpp:13: error: candidates are: int b2::operator[](double)
XXX.cpp:7: error: int b1::operator[](int)

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
#include <iostream>
using namespace std;

class b1
{
public:
int operator[](int i){ return 1; }
};

class b2
{
public:
int operator[](double f){ return 2; }
};

class C:
public b1,
public b2
{
};

int main( int argc, char** args )
{
    int x;
    C c;
    cout << c[x] << endl;
    return 0;
}
It's called the diamond problem and is solved (in C++) via virtual inheritance. Be familiar with this situation, it's a common interview question. ;)

Ok, I'll try actually reading the code from now on.

Last edited on
Try initializing X to a value and see if it wtill gives you the error...

you might be getting it because the varaible is "0x0000", for both a float and an int, there is no distinction...



Try doing this, I haven't tried it but it might work.

1
2
cout<<c::operator[](int x)<<endl;
cout<<c::operator[](double x)<<endl;


Also you should initialize x to something, even if you don't care what it is.
Only this is working:
cout << c.b1::operator[](x) << endl;
And it doesn't matter, if I initialise x. Seams not "super" for me...
Overloading only works within the same scope. You have two operator[] in two separate classes, and thus in two separate scopes. It's complaining about the name ambiguity because it must resolve scope before it can resolve overloading.

In other words, overloading cannot occur across multiple objects.

Not sure if this would work to resolve the issue, but try the following:

1
2
3
4
5
6
7
class C:
public b1,
public b2
{
	using b1::operator[];
	using b2::operator[];
};


That might bring both operators into the same scope and allow overloading to occur. I haven't tried it though.
Last edited on
test
Last edited on
Ambiguity checking occurs before type checking, so overloading is not possible across classes. I was surprised to see the results in MS Visual C++ 6.0. It actually returned 1! Looks like the user-friendly-compiler aims for giving as few errors as possible :)

I would like to see the base class as scope resolution operator in action here.
Last edited on
Topic archived. No new replies allowed.