See following code:
#include <iostream>
struct A { // Interface
virtual void a() = 0;
virtual void x() = 0;
};
struct B {
virtual void a() { std::cout << "B" << std::endl; }
};
struct C : A, B {
void a() override { B::a(); }
void x() override { std::cout << "x" << std::endl; }
};
int main() {
C c;
c.a();
c.x();
}
This code works. The question is if it is the best/optimal solution.
I wonder if there is any trick which allow me not to create a() in C class.
Update: I corrected the code to show why B cannot inherit from A.
Update 2:
#include <iostream>
struct I1 {
virtual void i1() = 0;
};
struct I2 {
virtual void i2() = 0;
};
struct I3 : I1, I2 {};
struct A : I1 {
void i1() override { std::cout << "i1" << std::endl; }
};
struct B : A, I2 {
void i2() override { std::cout << "i2" << std::endl; }
};
int main() {
B b;
b.i1();
b.i2();
I3* ptr = dynamic_cast<I3*>(&b); // warning: dynamic_cast of ‘B b’ to ‘struct I3*’ can never succeed
std::cout << ptr << std::endl;
}
The question is: How to pass pointer to 'b' via interface? Why b cannot be casted to I3 interface?