OOP Principles

Understand encapsulation, abstraction, inheritance and polymorphism well enough to explain them with your own examples and use them in code.

Beginner · about 8 hours · difficulty 2/5

Learn first: C++ for DSA

OOP questions appear in almost every placement interview, usually as "explain the four pillars with an example" followed by a follow-up that checks whether you really understand them. Memorised definitions fall apart at the follow-up, so learn each idea through code.

The four pillars, practically

  • Encapsulation: keep state private and expose behaviour. A BankAccount exposes deposit() and withdraw() that enforce rules; nobody sets balance directly.
  • Abstraction: callers depend on *what* something does, not *how*. An interface PaymentMethod with pay(amount) hides whether it is UPI, card or wallet.
  • Inheritance: an "is-a" relationship that reuses behaviour. Useful, but deep hierarchies become rigid.
  • Polymorphism: one call, many behaviours. Runtime polymorphism is method overriding through a base reference (virtual functions in C++); compile-time polymorphism is overloading and templates/generics.

Ideas interviewers probe next

  • Composition over inheritance: a Car *has an* Engine rather than *being* one. Prefer composition when the relationship is "has-a" or behaviour needs to change at runtime.
  • Abstract class vs interface: an abstract class can hold state and partial implementation; an interface is a pure contract (Java allows multiple interfaces, single class inheritance).
  • Access modifiers, constructors, destructors, static members, and in C++ the virtual destructor rule for base classes.
  • Overloading vs overriding, and why overriding needs the same signature.

Pitfalls

  • Using inheritance only to reuse code, which creates fragile "is-a" claims that are not true.
  • Getters and setters for every field, which is encapsulation in name only.

Good enough to move on: you can design a small class hierarchy for shapes or payment methods, explain each pillar using it, and justify one place where you chose composition.

Key concepts

  • Classes, objects and constructors
  • Encapsulation and access modifiers
  • Abstraction with interfaces
  • Inheritance and its limits
  • Runtime vs compile-time polymorphism
  • Abstract class vs interface
  • Composition over inheritance
  • Virtual functions and vtables: C++ internals often asked in product companies

Mini project

Build a console payment system with a PaymentMethod interface and UPI, Card and Wallet implementations, a Wallet that composes a TransactionHistory, and a checkout function that works with any PaymentMethod. Write a short README mapping each OOP pillar to a line of your code.

Check yourself

Give an example where inheritance is the wrong choice and composition is better, and explain what breaks if you use inheritance there.

Free resources