⚙️ C++ Beginner

What are the four pillars of OOP in C++?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex C++ topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

C++ supports all four pillars of Object-Oriented Programming: (1) Encapsulation: bundling data (member variables) and methods (member functions) that operate on that data within a class, and restricting direct access using access specifiers. class BankAccount { private: double balance; // hidden public: void deposit(double amount) { if (amount > 0) balance += amount; } double getBalance() const { return balance; } }; Encapsulation protects invariants and hides implementation details; (2) Abstraction: exposing only essential features and hiding complexity. Pure virtual functions define abstract interfaces: class Shape { public: virtual double area() const = 0; // pure virtual virtual ~Shape() = default; }; Clients use Shape without knowing the concrete implementation; (3) Inheritance: a derived class inherits members from a base class, enabling code reuse and "is-a" relationships. class Circle : public Shape { double radius; public: Circle(double r) : radius(r) {} double area() const override { return 3.14159 * radius * radius; } }; Types: public, protected, private inheritance. Multiple inheritance is supported; (4) Polymorphism: the same interface behaves differently based on the actual type. Compile-time (function overloading, templates) and runtime (virtual functions — dynamic dispatch via vtable): Shape* s = new Circle(5); std::cout << s->area(); // Calls Circle::area(). Virtual dispatch enables programming to interfaces, not implementations.

Pro Tip

This topic has C++-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.