aboutsummaryrefslogtreecommitdiff
path: root/examples/cxx/serializer/polymorphism/supermen.hxx
blob: e4e448fe109bd989d1add39604db31ec8d2b2b08 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// file      : examples/cxx/serializer/polymorphism/supermen.hxx
// copyright : not copyrighted - public domain

#ifndef SUPERMEN_HXX
#define SUPERMEN_HXX

#include <string>
#include <vector>

// Custom type id. We could also use standard C++ typeid/type_info
// if it is available.
//
enum type_id
{
  person_type,
  superman_type,
  batman_type
};

//
//
struct person
{
  virtual
  ~person ()
  {
  }

  person (const std::string& name)
      : name_ (name)
  {
  }

  const std::string&
  name () const
  {
    return name_;
  }

  void
  name (const std::string& n)
  {
    name_ = n;
  }

  virtual type_id
  type () const
  {
    return person_type;
  }

private:
  std::string name_;
};

//
//
struct superman: person
{
  superman (const std::string& name, bool can_fly)
      : person (name), can_fly_ (can_fly)
  {
  }

  bool
  can_fly () const
  {
    return can_fly_;
  }

  void
  can_fly (bool cf)
  {
    can_fly_ = cf;
  }

  virtual type_id
  type () const
  {
    return superman_type;
  }

private:
  bool can_fly_;
};

struct batman: superman
{
  batman (const std::string& name, unsigned int wing_span)
      : superman (name, true), wing_span_ (wing_span)
  {
  }

  unsigned int
  wing_span () const
  {
    return wing_span_;
  }

  void
  wing_span (unsigned int ws)
  {
    wing_span_ = ws;
  }

  virtual type_id
  type () const
  {
    return batman_type;
  }

private:
  unsigned int wing_span_;
};

// Poor man's polymorphic sequence which also assumes ownership of the
// elements.
//
struct supermen: std::vector<person*>
{
  ~supermen ()
  {
    for (iterator i = begin (); i != end (); ++i)
      delete *i;
  }
};

#endif // SUPERMEN_HXX