// how can I access A::a?

D

dick

/* multi_level_inheritance.cpp */
struct A
{
int a;
};

struct B1 : public A
{
int a;
};

struct B2 : public A
{
int a;
};

struct C : public B1, public B2
{
int a;
};

int main()
{
C ccc;

ccc.a=123;

ccc.B1::a=456;

/* 0030 */ ccc.B1::A::a=789;

}

// c++ multi_level_inheritance.cpp
// multi_level_inheritance.cpp: In function int main():
// multi_level_inheritance.cpp:30: error: A is an ambiguous base of C


// how can I access A::a?
 
C

Carlo Milanesi

struct A
{
int a;
};

struct B1 : public A
{
int a;
};

struct B2 : public A
{
int a;
};

struct C : public B1, public B2
{
int a;
};

If I go on with:

#include <iostream>
int main() {
C ccc;
ccc.a=123;
ccc.B1::a=234;
ccc.B2::a=345;
ccc.B1::A::a=456;
ccc.B2::A::a=567;
std::cout << ccc.a << " " << ccc.B1::a << " "
<< ccc.B2::a << " " << ccc.B1::A::a << " "
<< ccc.B2::A::a;
}

.... and then I compile and run this program, I get as output:
123 234 345 456 567

What's the problem?
 
C

Carlo Milanesi

My g++ compiler did not compile the code.


What compiler did you use?

I used Microsoft (R) 32-bit C/C++ Optimizing Compiler version
15.00.30729.01 for 80x86, included with Visual Studio 2008.
Now I just tested it also with g++ 4.3.2 for Linux and actually I got
for 4 times the compilation error: ‘A’ is an ambiguous base of ‘C’.

I think GCC is wrong.
 
V

Victor Bazarov

There are two A::a's, which is why the error message said that the
reference to A is ambiguous. You need to decide which one you want to
access, then name it. Hint: there's one in B1 and one in B2.

And does the fact that the OP specifically used 'B1::' before 'A::a'
matter not?

V
 
V

Victor Bazarov

Sure, but you're giving away the ending. There's clearly a problem in
the line ccc.a = 123; so it's not at all likely that the only error
message came from the line marked /* 0030 */.

Actually, since 'C' has a member 'a', which hides *both* 'B1::a' and
'B2::a' (which in turn hid both 'A::a' from base class 'A'), I would not
expect to see an error in 'ccc.a = 123;'. Just saying...
On the other hand, it does help to carefully read the code in question. :-(

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top