Xref: utzoo comp.lang.c++:6440 comp.object:925 Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!iuvax!purdue!mentor.cc.purdue.edu!gza From: gza@mentor.cc.purdue.edu (William R Burdick) Newsgroups: comp.lang.c++,comp.object Subject: Re: Inheritance vs. Composition Message-ID: Date: 13 Feb 90 07:55:37 GMT References: Sender: news@mentor.cc.purdue.edu Followup-To: comp.lang.c++ Organization: Team Cthulhu Lines: 38 The difference between inheritance (or generalization) and composition (or aggregation) is a tough point to figure out without some good examples (I hope I can give some here). Depending on what language you use and what you use your objects for, you may not be able to tell what the difference is right off. Mainly, inheritance passes on behavior to subclasses and composition passes on form to aggregations. As an easy way to tell the difference right off (using multiple inheritance), consider readable files, writable files, and read-write files. You can say that a read-write file inherits behavior from readable files and writable files. If you were to try to make a read-write file out of a composition, you might end up with an object containing two files, a readable file and a writable file. If you make a Read-Write File (the class) a subclass of Read File and Write File, you get a kind of file which can be read from and written to. classes use inheritance and classes are definitions of objects. Instances use composition, and instances are the objects. A particular read-write file does not inherit behavior from its superclass because it is not a class, it is a file, while a read-write file could be composed of a read file and a write file. When you want to model objects which are made of other objects, use composition, when you want to model objects which behave like other kinds of objects, use inheritance. The key words here are 'made of,' 'other objects,' 'behave like,' and 'kinds of objects.' When I use 'kinds of objects,' I am referring to objects of other classes, when I use 'other objects,' I am referring to just any other objects. An object composed of other objects shares a 'made-of/part-of' relationship with those objects, while a class shares a 'has-a/is-a' relationship with its subclasses. In OOPLs, you can use instance variables for the part-of relationship and you can use subclassing for the is-a relationship. -- -- Bill Burdick burdick@cello.ecn.purdue.edu