fork download
  1. #include <iostream>
  2.  
  3. class base
  4. {
  5. public:
  6. base(int size) : size_(size) {}
  7.  
  8. virtual int get_size() const { return size_; }
  9.  
  10. private:
  11. int size_;
  12. };
  13.  
  14. std::ostream& operator<<(std::ostream& os, const base& obj) {
  15. os << "base size=" << obj.get_size() << std::endl;
  16. return os;
  17. }
  18.  
  19. class derived1 : public base
  20. {
  21. public:
  22. derived1(int size) : base(size) {}
  23.  
  24. virtual int get_size() const {
  25. return 2 * base::get_size();
  26. }
  27. };
  28.  
  29. std::ostream& operator<<(std::ostream& os, const derived1& obj) {
  30. os << "derived1 size=" << obj.get_size() << std::endl;
  31. return os;
  32. }
  33.  
  34. int main(int argc, char* argv[]) {
  35.  
  36. base* b1 = new base(3);
  37. std::cout << "b1 size is: " << b1->get_size() << std::endl;
  38.  
  39. std::cout << b1 << std::endl;
  40. std::cout << *b1 << std::endl;
  41.  
  42. base* b2 = new derived1(4);
  43. std::cout << "b2 size is: " << b2->get_size() << std::endl;
  44.  
  45. std::cout << b2 << std::endl;
  46. std::cout << *b2 << std::endl;
  47.  
  48. delete b1;
  49. delete b2;
  50. return 0;
  51. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
b1 size is: 3
0x8e02008
base size=3

b2 size is: 8
0x8e02018
base size=8