How to call the function sum from instance of class E without modifying the class definitions. I have define 2 classes with same function. And inherited both of them in two different classes. Now how can i access the sum from object E.
class A {
public:
int sum(int a, int b) {
return a b;
}
};
class F {
public:
int sum(int a, int b) {
return a b;
}
};
class B: public A, public F {
};
class C: public A, public F {
};
class E: public B, public C {
};
int32_t main() {
E d;
cout << d.A::B::sum(3, 4);
}
CodePudding user response:
static_cast<B&>(d).A::sum(3, 4);
CodePudding user response:
While @IgorTandetnik's answer is valid, it is not what I would recommend.
The sum()
methods you described should simply not be methods. They don't require privileged access to other members of classes A and B respectively, so - they should simply be freestanding functions (or at most: static methods). This is principle C.4 of the C coding guidelines.
If you minimize a class' set of methods to those which are actually necessary, you will have a lot fewer cases of such ambiguity; and your classes will likely be easier to understand and maintain.
In your case, you even have two methods with related functionality, so it's possible you might be able to have a single sum()
function (perhaps templated?) for both classes.