Title: Class Composition contd'
1Class Composition contd.
- Container classes.
- Example.
2Container Classes
- A composite class is a class whose objects
contain data members that are objects of other
classes (called component classes). - A container class is a special kind of composite
classes. The objects of a container class contain
an array of objects of anoher class. - A container class object will contain an array
of objects of the component class, and the
methods of the container class should be designed
to implement useful functions such as array
search, sorting, adding an element to the array - The component class should be designed so that
its objects can be manipulated in the container
class, e.g. providing modifier and selector
methods, implement operator overloading - Note a modifier method changes the value of a
data member, while a selector method returns the
value of a data member.
3Example
include ltiostreamgt include ltstdio.hgt using
namespace std const int AlbumSize10 class
Picture private double width double
height bool color public Picture (double
w0, double h0, bool c0) width wheight
h color c void setwidth(double w)width
w void setheight(double h)height h void
setcolor(bool c)color c float
getwidth()return width float
getheight()return height bool
getcolor()return color bool operatorgt
(Picture P) if (P.widthP.height gt
widthheight) return false else return
true
4Example contd.
class Album private Picture picAlbumSize in
t count public Album() count(0) void
addpic(Picture p) count piccount-1
p void removepic(int i) for (int ji j lt
count j) if (j ! AlbumSize-1) picj
picj1 else break count-- void
print () cout ltlt "Pictures in album" ltlt
endl cout ltlt "width\t" ltlt "height\t" ltlt
"type" ltlt endl for (int j0 jltcount j)
printf("2.1f\t, 2.1f\t, i\n",
picj.getwidth(), picj.getheight(),
picj.getcolor())
5Example contd.
int main () Picture p1(4.5, 5.5, 0) Picture
p2(3.7, 18, 1) Album collection1 collection1.a
ddpic(p1) collection1.addpic(p2) collection1.p
rint() collection1.removepic(0) collection1.pr
int() return 0
Pictures in album width height type 4.5
5.5 0 3.7 18.0 1 Pictures in
album width height type 3.7 18.0 1