What is the difference between composition and inheritance?

Composition and inheritance are two of the most important programming techniques in Object-Oriented Programming (OOP). Let’s discuss each of them one by one.

Composition

In composition, a class contains one or more objects of other classes as private members to use the functionalities of other classes through their objects.

Composition is a ‘has-a’ relationship between classes. For example, a car has an engine, and a person has a heart, etc.

Visual depiction of composition

Composition allows the reusability of code while having classes and objects being loosely coupled, so that changing codes is easier.

Let’s look at the following code to understand composition.

#include <iostream>
using namespace std;
class Engine{
//engine class has private attribute for horsepower
private:
int horsepower;
public:
//setter and getter
void setHorsepower(int x){
horsepower = x;
}
int getHorsepower(){
return horsepower;
}
};
class Car{
//car class has an engine object and another variable as private attributes
private:
int model;
Engine obj;
public:
Car(int m, int h){
model = m;
obj.setHorsepower(h);
}
void display(){
cout << "Model = " << model << endl;
cout << "HorsePower = " << obj.getHorsepower() << endl;
}
};
int main() {
//making a car object and passing attributes
Car toyota(2020, 140);
toyota.display();
return 0;
}

The Car class uses the Engine class through its object to store the horsepower. This is an example of composition.

Inheritance

In inheritance, a class directly acquires all the attributes and methods of another class or classes and then extends or specializes them.

Inheritance is an ‘is-a’ relationship between classes. For example, a teacher is a person, and an apple is a fruit, etc.

Visual

Inheritance also allows reusability of the code by removing code redundancy. However, it binds the classes closely. As a result, changing the code in the parent class must be done carefully, since it affects the child classes as well.

Let’s look at the following code to understand inheritance.

#include <iostream>
#include<string>
using namespace std;
class Person{
private:
string name;
char gender;
public:
Person(string n, char g){
name = n;
gender = g;
}
void display(){
cout << "Name : " << name << endl;
cout << "Gender : " << gender << endl;
}
};
class Teacher: public Person{
private:
string designation;
double salary;
public:
Teacher(string n, char g, string d, double s) : Person(n, g){
designation = d;
salary = s;
}
void display(){
Person::display();
cout << "Designation : " << designation << endl;
cout << "Salary : " << salary << endl;
}
};
int main() {
Teacher obj("Mike Spencer", 'M', "Assistant Professor", 3000);
obj.display();
return 0;
}

The Teacher class can call the Person class’s member functions. This is the result of inheritance.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved