Interview Q&A · C++ · 8 questions in this topic

The Four OOP Pillars in C++ — C++ Interview Q&A

All C++ topics

Encapsulation, abstraction, inheritance and polymorphism — what each one concretely means in C++ code. Part of Classes & OOP Pillars · 213 questions in the C++ bank.

What is encapsulation and how does C++ implement it?

Answer

Encapsulation bundles data with the operations on it and hides internals behind an interface. C++ implements it with classes plus access specifiers (private/protected/public), const-correct interfaces, and invariants enforced by constructors and mutators.

Good encapsulation means callers depend on behavior, not representation — the member layout can change without breaking users.

Example

Example.cppcpp
class BankAccount {
public:
    void deposit(double a) { if (a > 0) balance_ += a; }
    double balance() const { return balance_; }
private:
    double balance_ = 0; // invariant: never negative via interface
};

What is abstraction in C++?

Answer

Abstraction exposes what an object does while hiding how it does it. In C++ it is expressed through public interfaces, abstract base classes / pure virtual functions, and templates that program to concepts rather than concrete types.

A std::sort caller, for example, depends only on iterator requirements — not on the introsort implementation underneath.

Example

Example.cppcpp
struct Shape { virtual double area() const = 0; virtual ~Shape() = default; };
struct Circle : Shape {
    explicit Circle(double r) : r_(r) {}
    double area() const override { return 3.14159 * r_ * r_; }
private:
    double r_;
};

What is inheritance and what are its access modes?

Answer

Inheritance derives a new class from a base, reusing and extending its interface. C++ has public (IS-A: base interface stays public), protected (public/protected base members become protected) and private (IS-implemented-in-terms-of: everything becomes private) inheritance.

Public inheritance models substitutability; private inheritance models reuse without substitutability (often better expressed as composition).

Example

Example.cppcpp
class Animal { public: virtual void speak() const {} };
class Dog : public Animal { // IS-A: Dog is an Animal
public:
    void speak() const override {}
};

💡 Say IS-A for public, implemented-in-terms-of for private — that phrasing is exactly what interviewers listen for.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits