-
Inheritence ambiguity
I have a base class A, which is publicly inherited by both B and C. D is a class that public inherits B and C. There is some ambiguity when I make a certain function call.
Code:
#include <iostream>
using namespace std;
class A
{
private:
int Aint;
public:
A():Aint(1) {}
~A() {}
virtual int GetAint(void) {cout << "A::GetAint()" << endl; return Aint; }
};
class B : public A
{
private:
int Bint;
public:
B():Bint(2) {}
~B() {}
virtual int GetBint(void) {return Bint; }
virtual int GetAint(void) {cout << "B::GetAint()" << endl; return A::GetAint(); }
};
class C : public A
{
private:
int Cint;
public:
C():Cint(3) {}
~C() {}
virtual int GetCint(void) {return Cint; }
virtual int GetAint(void) {cout << "C::GetAint()" << endl; return A::GetAint(); }
};
class D : public B, public C
{
private:
int Dint;
public:
D():Dint(4) {}
~D() {}
virtual int GetDint(void) {return Dint; }
};
int main(void)
{
D d;
int temp;
temp=d.GetAint();
cout << temp << endl;
return 0;
}
The call 'd.GetAint()' is ambiguous, and rightly so, because that was the plan all along. My question is, what is the work around here? Can I specify in main() to call a particular inherited function, something like:
Code:
temp=d.C:GetAint();
I know that's not correct but is this possible?
I am also aware that I could just place a function in D and call whichever one I wanted.
-
Not sure if its really correct, but this does seem to work...
Code:
temp=d.B::GetAint();
When I change to that, my output is like this:
B::GetAint()
A::GetAint()
1
-
Ha! I didn't think it was so easy, so I didn't even try that. Thanks. Now for the crunch question: find me a real life application of classes that would result in this kind of ambiguity.
-
What about this:
Code:
temp=d.B.A::GetAint();
cout << temp << endl;
Using the same classes as before. Seeing as A::GetAint() is publicly inherited throughout, it should be possible to access it from an instance of D. What is the syntax for this?