peterdcasey

Untitled

May 15th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. class A {
  8. public:
  9.     explicit A(int num = 0)
  10.     : number{num} {
  11.         cout << "A constructor" << endl;
  12.     }
  13.  
  14.     A(const A& other) {
  15.         number = other.number;
  16.         cout << "A copy constructor" << endl;
  17.     }
  18.  
  19.     ~A() {
  20.         cout << "A destructor" << endl;
  21.     }
  22.  
  23.     virtual string toString() const {
  24.         return "A: " + to_string(getNumber());
  25.     }
  26.  
  27.     int getNumber() const {
  28.         return number;
  29.     }
  30.  
  31. private:
  32.     int number;
  33. };
  34.  
  35. class B : public A {
  36. public:
  37.     B(int num = 0)
  38.     : A(num) {
  39.         cout << "B constructor" << endl;
  40.     }
  41.  
  42.     ~B() {
  43.         cout << "B destructor" << endl;
  44.     }
  45.  
  46.     virtual string toString() const override {
  47.         return "B: " + to_string(getNumber()) + " " + A::toString();
  48.     }
  49.  
  50. private:
  51.  
  52. };
  53.  
  54. ostream& operator<<(ostream& out, const A* obj) {
  55.     out << obj->toString();
  56.     return out;
  57. }
  58.  
  59. ostream& operator<<(ostream& out, const A& obj) {
  60.     out << obj.toString();
  61.     return out;
  62. }
  63.  
  64. int main()
  65. {
  66.     A* obj = new A{'A'};
  67.     B* obj2 = new B{'Z'};
  68.     B  obj3{'B'};
  69.  
  70.     vector<A*> v{obj, obj2, &obj3};
  71.  
  72.     for (auto item : v) {
  73.         cout << item << endl;
  74.     }
  75.     /*
  76.     cout << obj << endl;
  77.     cout << obj2 << endl;
  78.     cout << &obj3 << endl;
  79.     cout << obj3 << endl;
  80.     */
  81.     delete obj2;
  82.     delete obj;
  83.     return 0;
  84. }
Add Comment
Please, Sign In to add comment