Listing 2: Test case for GenericInstrument and Configuration classes
1: #include "instrument.h"
2: #include <new.h> // for placement new
3: #include <iostream.h>
4: #include <assert.h>
5:
6: class Piano : public Instrument {
7: int attr; // an attribute
8: public:
9: Piano() {
10: assert(sizeof(*this) <= sizeof(GenericInstrument));
11: }
12: virtual void playNote(Note key);
13: };
14:
15: class Violin : public Instrument {
16: int attr1; // an attribute
17: int attr2; // another attribute
18: public:
19: Violin() {
20: assert(sizeof(*this) <= sizeof(GenericInstrument));
21: }
22: virtual void playNote(Note key);
23: };
24:
25: void Piano::playNote(Note key) {
26: cout << "Piano " << key << endl;
27: }
28:
29: void Violin::playNote(Note key) {
30: cout << "Violin " << key << endl;
31: }
32:
33: static Configuration c1, c2;
34:
35: int main() {
36: new(&c1.i) Piano; // instantiate Piano
37: c1.i.playNote('c');
38: memcpy(&c2, &c1, sizeof(Configuration));
39: static_cast<Instrument *>(&c2.i)->playNote('d');
40:
41: new(&c1.i) Violin; // instantiate Violin
42: c1.i.playNote('e');
43: c1 = c2; // Oops, doesn't copy the v-pointer!
44: c1.i.playNote('f');
45:
46: return 0;
47: }