|
| 1 | +// Composition of classes 2 |
| 2 | +/* |
| 3 | + Person class has a member of type Birthday: |
| 4 | + Composition is used for objects that share a has-a relationship, as in "A Person has a |
| 5 | + Birthday */ |
| 6 | + |
| 7 | +class Person { |
| 8 | + public: |
| 9 | + Person(string n, Birthday b) |
| 10 | + : name(n), |
| 11 | + bd(b) |
| 12 | + { |
| 13 | + } |
| 14 | + private: |
| 15 | + string name; |
| 16 | + Birthday bd; |
| 17 | +}; |
| 18 | + |
| 19 | +// EXAMPLE2 |
| 20 | +#include <iostream> |
| 21 | +using namespace std; |
| 22 | + |
| 23 | +class Birthday{ |
| 24 | +public: |
| 25 | + Birthday(int d, int m, int y) |
| 26 | + :Day(d),Month(m),Year(y){ |
| 27 | + } |
| 28 | + |
| 29 | + void PrintBirthday(){ |
| 30 | + cout << Day << "/" << Month << "/" << Year << endl; |
| 31 | + } |
| 32 | +private: |
| 33 | + int Day, Month, Year; |
| 34 | +}; |
| 35 | + |
| 36 | +class People{ |
| 37 | +public: |
| 38 | + People(string name, Birthday bd) |
| 39 | + :Name(name), Birth(bd){ |
| 40 | + } |
| 41 | +void PrintInfo(){ |
| 42 | + cout << "Name: " << Name << "\n" << "Birthday: "; |
| 43 | + Birth.PrintBirthday(); |
| 44 | + } |
| 45 | +private: |
| 46 | + string Name; |
| 47 | + Birthday Birth; |
| 48 | +}; |
| 49 | + |
| 50 | +int main(){ |
| 51 | + Birthday Birthday1st(15,10,2003); |
| 52 | + People People1st("Adrit",Birthday1st); |
| 53 | + |
| 54 | + People1st.PrintInfo(); |
| 55 | + return 0; |
| 56 | + |
| 57 | +} |
| 58 | + |
| 59 | +// ''People's'' constructor, taking two parameters and initializing its private members: name and dateOfBirth |
| 60 | +People::People(string x, Birthday bo) |
| 61 | + :name(x), dateOfBirth(bo) |
| 62 | + { |
| 63 | + } |
| 64 | + |
| 65 | +// a printInfo() function |
| 66 | +// Notice that we can call the bd member's printDate() function, since it's of type Birthday, which has that function defined |
| 67 | + |
| 68 | +class Person { |
| 69 | + public: |
| 70 | + Person(string n, Birthday b) |
| 71 | + : name(n), |
| 72 | + bd(b) |
| 73 | + { |
| 74 | + } |
| 75 | + void printInfo() |
| 76 | + { |
| 77 | + cout << name << endl; |
| 78 | + bd.printDate(); |
| 79 | + } |
| 80 | + private: |
| 81 | + string name; |
| 82 | + Birthday bd; |
| 83 | +}; |
| 84 | + |
| 85 | +// define the printInfo() function, which prints ''People's'' name and birthdate, using dateOfBirth's printDate() function |
| 86 | + |
| 87 | +void People::printInfo () |
| 88 | +{ |
| 89 | + cout << name << endl; |
| 90 | + dateOfBirth .printDate (); |
| 91 | +} |
| 92 | + |
| 93 | + |
0 commit comments