| Module | Programming in C++ |
| Title | Session 7 - Overview |
| Authors | Ross Paterson, Christos Kloukinas |
| Default appearance | |
| Large text | |
Multiple inheritance
[Stroustrup 15.2]
A simple solution for exercise 1.a is the following:
#include <iostream>
#include <cassert>
using namespace std;
class A {
public:
int x; /* The state of A. Without members (fields), an object has no state. */
A( int i = 0 ) : x(i) {
/* for 1.c - uncomment & add similar constructors to B, C, and D, with different default argument values. */
/* cout << "A(" << i << ")\n"; */
}
};
class B : public /* virtual */ A { /* uncomment virtual for 1.b */
};
class C : /* virtual */ public A { /* uncomment virtual for 1.b */
};
class D : public B, public C {
};
int main() {
D d;
/** There are two ways to access the x of a particular object. */
/** (a) By qualification: */
d.B::x = 1; /* set the x from the B side of D to 1 */
d.C::x = 2; /* set the x from the C side of D to 2 */
cout << "d.B::x and d.C::x are" << (( &(d.B::x) == &(d.C::x) )? "" : " *not*") << " the same!\n";
/** (b) By restricting the object's interface to a particular base interface: */
B &b = d; /* refer to the B part of the D object */
C &c = d; /* refer to the C part of the D object */
cout << "b.x and c.x are" << (( &(b.x) == &(c.x) )? "" : " *not*") << " the same!\n";
assert( &(d.B::x) == &(b.x) );
assert( &(d.C::x) == &(c.x) );
cout << "The B side x is " << d.B::x << " or " << b.x << endl;
cout << "The C side x is " << d.C::x << " or " << c.x << endl;
return 0;
}