CoolInterview.com - World's Largest Collection of Interview Questions
Send Free SMS
 Interview Questions  
 Our Services  


INTERVIEW QUESTIONS LANGUAGES C++ DETAILS
Question :
What is the difference between composition and inheritance?

Posted by: pavan mainde on 11/20/2007

Contact pavan mainde  Contact pavan mainde
Category C++ Interview Questions
Rating (5.0) By 17 users
Added on 11/20/2007
Views 4918
Rate it!
Answers:

Composition is the technique of combining the simpler data types with the complex data types e.g. function calls within the calling function.
Inheritance is one, in which one can acquire the property of other..



 Posted by: vinod rajput    

Contact vinod rajput  Contact vinod rajput

Composition & inheritance is totally different from each other composition means compose the properties by code of same class in composition we can refer some other class who hold same properties but we have to code we can not directly use that code ,we have to rewrite .

But inheritance i.e inherit the properties of other class .in it method of class to whom we inherit can directly call by the child class object.

if we think as real life example if we inspired by someone we adope the properties of that person we have to add that quality of person ourself ,that is composition. but some quality of our parent automatically in us there is no need to strive ,that is inheritance



 Posted by: Deepak jain    

Contact Deepak jain  Contact Deepak jain

Let me be a bit elaborate. There are two kinds of inheritances. One if of the kind "IS A" and the other is of the kind "HAS A". "IS A" type of inheritance is like the following

class car:public vehicle
{
}
where it is said CAR "IS A [KIND OF ]" VEHICLE.

There are two kinds of "HAS A" inheritance implementation. Aggregation and Composition.

Now consider the following

class Heart
{
}

class HumanBeing
{
private :
Heart _heart;
}

The above example is that of "COMPOSITION" type of "HAS A" Inheritance. The Human Being "HAS A" heart and human being can not live with out heart. There is no sense of the lifecycle of human without heart ( one verson of the academia ) and no lifecycle of heart without human ( another version of the academia ). So if one destroys human, the heart also gets destroyed. This is signified as "COMPOSITION".

Consider the following

class Sheep
{
}

class HerdOfSheep
{
private Sheep *_pSheep;
}

In the above case the HerdOfSheep can be empty and sheep can exist without being in the herd. This kind of "HAS A" relationship in inheritance is called as "AGGREGATION". The scope of sheep is even outside the scope of the herd.

-Parthasarathy



 Posted by: Parthasarathy    

Contact Parthasarathy  Contact Parthasarathy

Inheritance is a "Is A" relationship and composition is "Has A" relationship. Composition is for code reuse. Inheritance is not for code reuse but for flexibility.



 Posted by: Nagendra    

Contact Nagendra  Contact Nagendra

Composition - A class has the object of class B i.e we can access the member variable of class B through class A also.
ex.
Class B
{
}
Class A
{
A a;
}

Inheritance : If we say that class A inherit from Class B that means Class B has the characteristics of Class A (depending on the access modifier).



 Posted by: Amit    

Contact Amit  Contact Amit

We can say private inheritance is a syntactic variant of composition (has-a).

E.g., the "Car has-a Engine" relationship can be expressed using composition:

class Engine {
public:
Engine(int numCylinders);
void start(); // Starts this Engine
};

class Car {
public:
Car() : e_(8) { } // Initializes this Car with 8 cylinders
void start() { e_.start(); } // Start this Car by starting its Engine
private:
Engine e_; // Car has-a Engine
};

The same "has-a" relationship can also be expressed using private inheritance:

class Car : private Engine { // Car has-a Engine
public:
Car() : Engine(8) { } // Initializes this Car with 8 cylinders
Engine::start; // Start this Car by starting its Engine
};

There are several similarities between these two forms of composition:
* In both cases there is exactly one Engine member object contained in a Car
* In neither case can users (outsiders) convert a Car* to an Engine*

There are also several distinctions:
* The first form is needed if you want to contain several Engines per Car
* The second form can introduce unnecessary multiple inheritance
* The second form allows members of Car to convert a Car* to an Engine*
* The second form allows access to the protected members of the base class
* The second form allows Car to override Engine's virtual[20] functions


Use composition when you can, private inheritance when you have to.

Normally you don't want to have access to the internals of too many other
classes, and private inheritance gives you some of this extra power (and
responsibility). But private inheritance isn't evil; it's just more expensive
to maintain, since it increases the probability that someone will change
something that will break your code.

A legitimate, long-term use for private inheritance is when you want to build a
class Fred that uses code in a class Wilma, and the code from class Wilma needs
to invoke member functions from your new class, Fred. In this case, Fred calls
non-virtuals in Wilma, and Wilma calls (usually pure virtuals[22.4]) in itself,
which are overridden by Fred. This would be much harder to do with
composition.

class Wilma {
protected:
void fredCallsWilma()
{
cout << "Wilma::fredCallsWilma()
";
wilmaCallsFred();
}
virtual void wilmaCallsFred() = 0; // A pure virtual function[22.4]
};

class Fred : private Wilma {
public:
void barney()
{
cout << "Fred::barney()
";
Wilma::fredCallsWilma();
}
protected:
virtual void wilmaCallsFred()
{
cout << "Fred::wilmaCallsFred()
";
}
};




 Posted by: Richa gupta    

Contact Richa gupta  Contact Richa gupta

I too like to know the answer.



 Posted by: Prabhuraj    

Contact Prabhuraj  Contact Prabhuraj

Inheritance:- Two class can exhibits an IS_A relationship called inheritance.

Composition:- This concept comes under the containment(in which one(outer) object holds another(Inner) object). This shows the HAS_A relationship. In this type of containment the outer object controls the life time of the inner objects. e.g (outer)[Bank] HAS_A [Account](inner).



 Posted by: Jitendra singh    

Contact Jitendra singh  Contact Jitendra singh

Composition is nothing but the Has-A relationship which is indicates inner class is not independent from outer class .

This is creates the COHESION and dependencies and which is tightly coupled relationship and this is not recommended many times in OOPS .



 Posted by: Ashwinkumar    

Contact Ashwinkumar  Contact Ashwinkumar

Defining a class as a member of another class is composition.

A process by which object of one class acquire the properties of another class is inheritance.



 Posted by: Manoj Jangid    

Contact Manoj Jangid  Contact Manoj Jangid

java is object oriented program but another one is not.



 Posted by: tamil    

Contact tamil  Contact tamil

In a Class composition
the use of the class has clear knowledge of all the classes which are used in the composition. the classes appear as data members.

In inheritance the base class is totally "dismantled" and the use of the class has knowledge of the base class. all the methods and data members of the base class is the member of the new derived class. this is different from the above case in which the composing class it self appears as data member.



 Posted by: Amaren    

Contact Amaren  Contact Amaren

Composition means Creating object of one class in another class.

Inheritance means deriving a new class from already existing class.



 Posted by: Ravikumar Horatti    

Contact Ravikumar Horatti  Contact Ravikumar Horatti

From a Desing Perspective Favour Composition over Inheritance.
(1) Inheritance favours tight coupling.
(2) Compisition favours loose coupling.
(3) Inheritance: Any changes in the base class might have ripple effect in the derived class.
(4) Inheritance: Favours weak encapsulation.
(5) Composition: favours strong encapsulation.
(6) Inheritance is achieved by Extension.
(7) Composition is ahcieved by Instance variable.
(8) Inheritance is static binding, where as composition is dynamic binding.

As per design principle:
A class should be closed for modification and open for extension.



 Posted by: rakshith    

Contact rakshith  Contact rakshith


If you have the better answer, then send it to us. We will display your answer after the approval.
Name :*
Email Id :*
Answer :*
Verification Code Code Image - Please contact webmaster if you have problems seeing this image code Not readable? Load New Code
Process Verification  Enter the above shown code:*
Inform me about updated answers to this question

   
Related Questions
View Answer
What is void main mean?
View Answer
create six large matrices in subprogram (100*100) two static and three stack dynamic ...fill two static,two stack matrices with random numbers 1 to 100 ..the code in subprogram must perform large matrix multiplication on static matrices and should repeat this with stack dynamic ...compare and explain result?
View Answer
create six large matrices in subprogram (100*100) two static and three stack dynamic ...fill two static,two stack matrices with random numbers 1 to 100 ..the code in subprogram must perform large matrix multiplication on static matrices and should repeat this with stack dynamic ...compare and explain result?
View Answer
How can I set the background in flash like camera?( black color that some times for a specific time your background becomes white)
View Answer
HI, THIS PROGRAM MUST BE SUBMMITED AS SOON AS POSSIBLE.MAY YOU PLEASE HELP ME TO TACKLE IT ? I?LL BE VERY PLEASE IF I CAN GET HELP.





MULTICHOICE VIDEO RENTAL SHOP needs an Object Oriented program that process the following information about ten (10) videos in their stock
? The title, the director, the year produced and a list of main actors for each video. (If there are more than five main actors, include only the five most famous actors)
? The function setVideo that input information into each video object
? The function getVideo that displays information of a particular video on the screen
? A customer (identified by ID) plus his full names and address can borrow at most 2 videos @ R12.50 per day. A penalty of 10% per day is charged if returned late. The borrow period is at most 7 days
? Video titles should not exceed 25 characters in length. If that happens, truncate the length to a most 25 characters
? A video should be checked if is not rented out before borrow transaction is processed. If borrowed out the customer should either be requested for the second choice or be advised when the video is expected back in the shop
? Failure for the shop to receive the video back within 7 days, is considered permanent loss and the customer is liable to a R400.00 compensation fee
? Information about the number of films in stock at any point in time should be readily available
? At the end of business, a report should be generated showing
o Which films are rented out and when are they due
o To which customers they are borrowed to
o Which videos are left in stock
o How much money was collected for the day
Generate your own test data that will test all cases to illustrate the accuracy and consistency of your program

View Answer
what is abstractor in c++?
View Answer
I want a program on INLINE function and demonstrate the program with INLINE function and without INLINE function.Because i want to know clearly the difference between INLINE FUNCTION AND FUNCTION
View Answer
What is a friend function & its advantage?
View Answer
Where we use reference and where we use pointers ?Write their differences and advantages and disadvantages .
View Answer
what are the disadvantages of copy constructor??
View Answer

Please Note: We keep on updating better answers to this site. Subscribe to our newsletter to get notified when better answer is posted.

Notify me when better answer is posted!
Email:

View ALL C++ Interview Questions

User Options
Sponsored Links


Copyright ©2003-2010 CoolInterview.com, All Rights Reserved.
Privacy Policy | Terms and Conditions
Page URL: http://www.coolinterview.com/interview/12499/default.asp?cachecommand=bypass


Download Yahoo Messenger | Placement Papers| FREE SMS | ASP .Net Tutorial | Web Hosting | Free SMS | Dedicated Servers | Joke of the Day

0.86