fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. template<typename T>
  6. class counted_type {
  7. static size_t counter;
  8. protected:
  9. counted_type(){}
  10. static size_t next_id() {
  11. return counter += 1;
  12. }
  13. public:
  14. size_t id = next_id();
  15.  
  16. };
  17. template<typename T>
  18. size_t counted_type<T>::counter = 0;
  19.  
  20. class person: public counted_type<person> {
  21. using counted_type<person>::id;
  22.  
  23. string first_name, last_name;
  24. public:
  25.  
  26. person(string const &fname, string const &lname):
  27. first_name(fname), last_name(lname){}
  28.  
  29. string to_string() const {
  30. return first_name + ", " + last_name + ", " + std::to_string(id);
  31. }
  32. };
  33.  
  34. class fruit: public counted_type<fruit> {
  35. using counted_type<fruit>::id;
  36.  
  37. string kind;
  38. public:
  39. fruit(string const &kind): kind(kind){}
  40.  
  41. string to_string() const {
  42. return kind + ", " + std::to_string(id);
  43. }
  44. };
  45.  
  46. int main() {
  47. person people[] = {
  48. person("John", "Travolta"),
  49. person("Rocky", "Balboa"),
  50. person("Rick", "Grimes")
  51. };
  52.  
  53. for(const auto &p: people) {
  54. cout << p.to_string() << endl;
  55. }
  56.  
  57. fruit fruits[] = {
  58. fruit("banana"),
  59. fruit("apple"),
  60. fruit("peach")
  61. };
  62.  
  63. for(const auto &f: fruits) {
  64. cout << f.to_string() << endl;
  65. }
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
John, Travolta, 1
Rocky, Balboa, 2
Rick, Grimes, 3
banana, 1
apple, 2
peach, 3