fork download
  1. #include <cstdio>
  2. #include <memory>
  3.  
  4. class B {
  5. private:
  6. virtual B *clone_impl( ){ return new B( *this ); }
  7. protected:
  8. int b;
  9. public:
  10. explicit B( int x ): b( x ){ }
  11. B( const B &that ): b( that.b ){ }
  12. virtual ~B( ){ }
  13. std::shared_ptr<B> clone( ){ return std::shared_ptr<B>( clone_impl( )); }
  14. virtual void print( ) const { std::printf( "B: %d\n", b ); };
  15. };
  16.  
  17. class D: public B {
  18. private:
  19. D *clone_impl( ) { return new D( *this ); }
  20. protected:
  21. int d;
  22. public:
  23. D( int x ): B(x), d( x*2 ){ }
  24. D( const D &that ): B( that.b ), d( that.d ){ }
  25. ~D( ){ }
  26. std::shared_ptr<D> clone( ){ return std::shared_ptr<D>( clone_impl( )); }
  27. void print( ) const { std::printf( "D: %d, %d\n", b, d ); };
  28. };
  29.  
  30. int main(){
  31. B b(6);
  32. D d(42);
  33.  
  34. b.print( );
  35. d.print( );
  36.  
  37. B *bp = &d;
  38. bp->print( );
  39.  
  40. std::shared_ptr<B> bfromb = b.clone( );
  41. std::shared_ptr<B> bfromd = d.clone( );
  42. std::shared_ptr<D> dfromd = d.clone( );
  43. // std::shared_ptr<D> dfromb = b.clone( ); // ERR
  44. std::shared_ptr<B> bfrombp = bp->clone( );
  45. // std::shared_ptr<D> dfrombp = bp->clone( ); // ERR
  46.  
  47. bfromb->print( );
  48. bfromd->print( );
  49. dfromd->print( );
  50. bfrombp->print( );
  51. }
Success #stdin #stdout 0s 3064KB
stdin
Standard input is empty
stdout
B: 6
D: 42, 84
D: 42, 84
B: 6
D: 42, 84
D: 42, 84
D: 42, 84