OOP Interview Question

What is the difference between inheritance and composition?

Updated 2026-08-16 · Beginner friendly
Quick answer

Inheritance models an is a relationship, where a child class is a kind of the parent, and it reuses the parent by extending it. Composition models a has a relationship, where one class holds another class as a field and uses its behaviour. Modern advice is to favour composition because it is more flexible and creates looser coupling than deep inheritance.

Key takeaways
  • Inheritance models an is a relationship, while composition models a has a relationship.
  • Composition holds another class as a field, which keeps designs flexible and loosely coupled.
  • Modern advice is to favour composition over inheritance for most designs.

The simple test: is a versus has a

Ask yourself whether the relationship is an is a or a has a. A Dog is an Animal, so inheritance fits. A Car has an Engine, so composition fits. Getting this test right is most of the answer.

Inheritance example

class Animal { public: void eat() {} };
class Dog : public Animal { };   // Dog is an Animal
class Animal { void eat() {} }
class Dog extends Animal { }   // Dog is an Animal
class Animal:
    def eat(self): ...
class Dog(Animal):   # Dog is an Animal
    pass

Composition example

class Engine { public: void start() {} };
class Car {
    Engine engine;                 // Car has an Engine
public:
    void start() { engine.start(); }
};
class Engine { void start() {} }
class Car {
    private Engine engine = new Engine();  // Car has an Engine
    void start() { engine.start(); }
}
class Engine:
    def start(self): ...
class Car:
    def __init__(self):
        self.engine = Engine()   # Car has an Engine
    def start(self):
        self.engine.start()

Why teams often prefer composition

In the interview

The phrase interviewers love is favour composition over inheritance. Say inheritance for a clear is a relationship and composition for a has a relationship, then explain that composition keeps designs flexible. That single sentence signals real experience.

Frequently asked questions

Why is composition often preferred over inheritance?

Composition lets you swap the inner object at run time and avoids fragile deep hierarchies, so a change in a base class is less likely to break many children.

What is the fragile base class problem?

It is when a change to a parent class unexpectedly breaks child classes that depended on its behaviour, a common risk with deep inheritance.

Want the full OOP guide?

Read every OOP concept with notes, diagrams, and code in one place. Track your progress as you go.

Open the OOP guide All OOP questions