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