fork download
  1. #include <iostream>
  2. #include <list>
  3. #include <algorithm>
  4. #include <iterator>
  5. using namespace std;
  6.  
  7.  
  8. class A {
  9. int val;
  10. public:
  11. A(int x=0) : val(x){}
  12. A& operator= ( const A &rhs ) { return *this; }
  13. void show() { cout<<val<<" ";}
  14. int get() const { return val; }
  15. };
  16. class B: public A {
  17. public:
  18. B(int x=0) : A(x) {}
  19. B( const B& rhs) : A(static_cast<A>(rhs)) {}
  20. B(const A& rhs) : A(rhs) {} // <================= WITHOUT THIS CTOR, IT FAILS TO COMPILE
  21. B& operator= ( const A &rhs ) { return *this; }
  22. };
  23.  
  24. int main() {
  25. A a;
  26. B b;
  27. std::list < A > aa{ A(1), A(2), A(3)};
  28. std::list < B > bb;
  29. a = b; // works
  30. b = a; // works
  31. //std::copy(aa.begin(), aa.end(), bb.begin()); // ouch: to avoid
  32. //for (auto &x : bb) x.show(); // ouch !! only copies on existing elements
  33. std::copy(aa.begin(), aa.end(), back_inserter<list<B>>(bb));
  34. for (auto &x : bb) x.show(); cout<<endl;
  35. bb.assign(aa.begin(), aa.end());
  36. for (auto &x : bb) x.show(); cout<<endl;
  37. std::copy(bb.begin(), bb.end(), back_inserter<list<A>>(aa));
  38. std::copy(bb.begin(), bb.end(), aa.begin());
  39.  
  40. std::list <int> xx;
  41. std::transform (aa.begin(), aa.end(), std::back_inserter<list<int>>(xx), [](const A&a){return a.get();});
  42. std::copy(xx.begin(), xx.end(), std::ostream_iterator<int>(cout,";")); cout<<endl;
  43. return 0;
  44. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
1 2 3 
1 2 3 
1;2;3;1;2;3;