Composition vs. Inheritance

P

Pallav singh

Hi All

i have dout when to use Composition and Inheritance while designing
Module in C++

Thanks
Pallav
 
J

Juha Nieminen

Pallav said:
i have dout when to use Composition and Inheritance while designing
Module in C++

Rule of thumb: Can you say that "<derived class> is a <base class>"?
If yes, then maybe inheritance will work.

Moreover, the <base class> should usually be more abstract as a
concept than <derived class>, which should be a more concrete concept.

Example: Base class is a "widget" and derived class is a "button". You
can say "a 'button' is a 'widget'". A "widget" is a more abstract
concept because there are many things which can "be a widget", while
"button" is a more concrete concept because not so many things can "be a
button".

Example: A "dialog" class has two "button" widgets. You cannot say "a
'dialog' is a 'button'", ergo composition. "A 'dialog' has a 'button'."
 
S

sumsin

Hi All

i have dout when to use Composition and Inheritance while designing
Module in C++

Thanks
Pallav

First of all try to find out the various entities in your design. Then
for a group of similar entities try to generalize them, as Juha said
for various kind of buttons like Radio-Button and Push-Button, it is
possible to generalize them with a button class. So here you should
use inheritance, where Button would the generic class for Radio-Button
and Push-Button.
While in case of composition you should think about the ingredient of
the entity. As Juha said, in general most of the Dialog Boxes have
‘Ok’ and ‘Cancel’ buttons. So here you should use composition, where
your Dialog box is composed of with two Push-Buttons ‘Ok’ and
‘Cancel’.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top