the only disadvantage of inheritance is the increase in the number of classes (for big systems)
Main Topics
Browse All TopicsI've heard composition is a better approach to design than inheritance. I know the difference between the two --- has-a versus is-a --- but why would a programmer avoid inheritance and go for composition instead?
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Actually there is more to it then what qurpreets said. There are pros and cons for each method. The main thing is that composition is more simple to declare and implement then inheritance, because polymorphism and multiple inheritance which usually are the main cause for complexity, do not exist. This thing is also the main weakness of composition (and strength of inheritance),i.e. if you need to use polymorphism, you have to use inheritance and virtual functions. There are more things like access rights, but these are the main things.
The article pointed to by anup_s is a fairly good explanation of the issues.
> I've heard composition is a better approach to design
> than inheritance
I'm not sure it is better. The problem with inheritance is that it is used too much. Students of OO see inheritance as a fundamental construct and hence believe it should be used everywhere. It should not.
From the point of view of encapsulation/coupling, it is a poor choice - only friendship introduces stronger coupling between two classes than inheritance. Changing the base class will have a ripple down effect on all derived classes.
On the other hand, if you want to use your class polymorphically (i.e. you want to override some of its virtual functions) or you need access to protected members of the class then you have no choice.
>> the only disadvantage of inheritance is the increase in the number of classes (for big systems)
That is not the only dissadvantage. For example, inheritance allows only one instance of the base class. So if you inherit class Stove from class Burner you have a stove class that can support only one burner....
inheritance, public inheritance at least, is usually considered a "is a" relationship. if you can say X is a Y then X should be derived from Y So for example.
stove is a burner. No, don't use inheritance.
desk is a drawer. No, don't use inheritance.
car is a truck. Yes, use inheritance.
person is an animal. Yes, use inheritance.
composition is a "has a" relationship. If you can say that x has a Y, then you should use composition.
stove has a burner. Yes, use composition.
desk has a drawer. Yes, use composition
car has a truck. No, don't use composition.
person has an animal. No, don't use composition.
> X is a Y then X should be derived from Y
I am not sure this is right, I think it should be if X is a Y then X *could* be derived from Y.
If X is not going to be used polymorphically, there probably is no real reason to use inheritance, and if it is not required then you probably shouldn't use it. All you are achieving is some unecessary coupling between classes. Inheritance purely for the sake of taxonomy is probably not a good idea.
jasonclarke > there probably is no real reason to use inheritance
Here's one reason why you might still want to use inheritance, even if you don't plan to use polymorphism: semantic clarity. If Jow Programmer wants to model cars as a kind-of vehicle, and implements a CCar class with a CVehicle member (ie, uses composition), then it might me less semantically clear to Bill Programmer that CCar is actually a kind-of CVehicle. Self-documenting code, in my opinion, is a huge plus; especially when writing C++ code, which is inheritely complex.
$0.02
Compare Java or COM specs with C++: you will find that the big problems of C++ object model are the coupling of data and access functions, and the single virtual function table, that does not distinguish between private and public functions. This makes code sharing dependent on implementation. If you wan to change the internal implementation of a CVehicle class, by adding a hidden data field, you need not only to recompile all components that use this class or a derived CCar class; you must also distribute the vehicle.h file that includes all the private memeber info.
Why should the user of your CVehicle object care about the private data memebers and functions?
The way to overcome the problems of C++ is to avoid inheritance and provide only public interfaces while keeping the private implementation details hidden in a single opaque data member, usually represented as a void*.
class CVehicle {
public:
float GetSpeed() const;
CPoint GetLocation() const;
bool Accelerate(float pressure, float period);
bool Brake(float period);
private:
void* m_pVehicleImplementation;
}
To follow this path, you define all public functions for your class and in your implementation (Vehicle.cpp) file use the member functions of your private implementation object:
float CVehicle::GetSpeed() const
{
return (CVehicle_Implementation*)
}
To make life easier, it's possible to create an "interface" class that lists the public interface functions:
class CVehicleInterface
{
public:
float GetSpeed() const;
CPoint GetLocation() const;
bool Accelerate(float pressure, float period);
bool Brake(float period);
}
This makes it possible for your partner to implement
class CCar: public CVehicleInterface
{
public:
int GetNumberOfPassangers() const;
private:
CVehicle* m_pVehicle;
int m_NumberOfPassangers;
}
and use the GetSpeed() function of your CVehicle class without having to declare it explicitly in CCar.
Note that various COM frameworks and wizards, like ATL, help you to work this way, and automatically generate most of this code for you, and more (like defining a "property" Speed to be accessed as pCar->Speed implemented as pCar->GetSpeed() or pCar->SetSpeed(60) according to the way it apears in your program).
>> you will find that the big problems of C++ object model are the
>> coupling of data and access functions, and the single virtual function table,
there is no specification for even a single virtual function table anywhere in the C++ standard. The implimenter is free to handle virtual functions as he/she pleases. If he/she wants to use 100 virtual function tables, then he/she can. Or use none.
>> This makes code sharing dependent on implementation.
This is by design and is not really a weakness in the language C and C++ are based on the philosophy that execution time is of greatest importance. This allows the compiler to generate code that is much faster than java's code
>> Why should the user of your CVehicle object care about
>> the private data memebers and functions.
The user doesn't care, but the compiler does. The compiler may need to untilize these private members even if the programmer can't. This is especially true if there are inline functions--which are used to great extent in C++ and not available at all in Java. But even without inlines the compiler still needs to "know" about the private members, especially when it comes to construction, destruction, and assignment of objects.
>> The way to overcome the problems of C++ is to avoid inheritance
The top experts in the field all agree that you should avoid inheritance in C++. NO!!!
>> provide only public interfaces while keeping the private implementation
>> details hidden in a single opaque data member, usually represented
>> as a void*.
What you are refering to is the pimple design pattern. This is a very usefule pattern--for some cases. It is not something that should be used for every case!!! That is like suggesting that ALL data shoudl be stored in linked lists. That is rediculious. There are specific cases in which this can be useful. For other cases it would make progamming much more difficult and the progrmam much slower and would provide no benefit.
> usually represented , as a void*.
this would be unhelpful in the design of the impl class (the forwarding methods would all have to cast the pointer)- the type of the opaque pointer can be the type of the impl class, and this can be declared in the header using a forward reference - so the pointer is still opaque.
> Here's one reason why you might still want to use inheritance,
maybe not...if CVehicle and CCar are not really related for anything other than taxonomy then maybe the relationship is just confusing: CCar and CVehicle do not share a common interface so why introduce the relationship? (As an example consider a computer game with classes representing graphical game objects derived from say CSprite, you might have CCar, CPlane, CShip - it probably doesn't make sense to derive these things from CVehicle because they probably don't have anything in common that distinguishes these 'vehicle' sprites from any other type of sprite.)
Business Accounts
Answer for Membership
by: anup_sPosted on 2001-03-07 at 19:10:08ID: 5909566
Check the following link
avaworld/j w-11-1998/ jw-11- tech niques.htm l
http://www.javaworld.com/j
- Anup