Intermediate⏱️ 11 min📘 Topic 19 of 32

🏛️ Classes and Objects in C++ — OOP Basics Made Simple

Master C++ classes — fields, methods, constructors, destructors, access modifiers, encapsulation. Beginner-friendly intro to object-oriented programming with examples.

A class is a blueprint for objects. It bundles data (fields) and behavior (methods) together — the foundation of object-oriented programming.

📜 Anatomy of a class

class BankAccount {
private:
  std::string owner;
  double balance;

public:
  BankAccount(std::string name, double initial)
    : owner(name), balance(initial) {}

  void deposit(double amount) {
    balance += amount;
  }

  double getBalance() const { return balance; }
};

BankAccount a("Sam", 100.0);
a.deposit(50);
std::cout << a.getBalance(); // 150

🔒 Access modifiers

  • public — accessible from anywhere
  • private — only from inside the class (default for class)
  • protected — class + its subclasses

🛠️ Constructors and destructors

  • Constructor: same name as the class. Runs at object creation.
  • Destructor: ~ClassName(). Runs at destruction.

💡 The 4 OOP pillars

  1. Encapsulation — hide data behind methods
  2. Abstraction — expose what, hide how
  3. Inheritance — derive classes from a base
  4. Polymorphism — one interface, many forms

💻 Code Examples

Rectangle class

class Rectangle {
private:
  double width, height;
public:
  Rectangle(double w, double h) : width(w), height(h) {}
  double area() const  { return width * height; }
  double perimeter() const { return 2 * (width + height); }
};

Rectangle r(4, 5);
std::cout << r.area() << ' ' << r.perimeter();
Output:
20 18

Constructor + destructor logging

class Logger {
public:
  Logger()  { std::cout << "create "; }
  ~Logger() { std::cout << "destroy "; }
};
int main() {
  Logger a;
  { Logger b; }    // b is destroyed here
}                  // a is destroyed here
Output:
create create destroy destroy

⚠️ Common Mistakes

  • Making all fields public — defeats encapsulation. Keep state private; expose methods.
  • Forgetting to initialize fields in the constructor — they get garbage values.
  • Using `this->member` everywhere when it's not needed — just `member` is fine if no ambiguity.
  • Not declaring const methods as `const` — limits how they can be called.

🎯 Interview Questions

Real questions asked at top product and service-based companies.

Q1.What is a class in C++?Beginner
A user-defined type that bundles data (fields) and behavior (methods). It's a blueprint — you create OBJECTS (instances) from it that each hold their own copy of the fields.
Q2.What is the difference between a class and an object?Beginner
Class = blueprint (the definition). Object = an instance of that class (an actual variable).
Q3.What is encapsulation?Intermediate
Hiding the internal state behind a controlled interface (methods). Fields are private; public methods are the only way to read/modify them.
Q4.What's a constructor and when is it called?Intermediate
A special method with the same name as the class, no return type. Called automatically when an object is created. Use it to initialize fields and acquire resources.
Q5.What does `const` after a method mean?Intermediate
`void print() const;` declares the method does NOT modify the object. Required to call from a `const` object.

🧠 Quick Summary

  • Class = blueprint with data + methods.
  • Object = an instance of a class.
  • private hides state; public exposes interface.
  • Constructor initializes; destructor cleans up.
  • Mark read-only methods with `const`.
  • Four OOP pillars: encapsulation, abstraction, inheritance, polymorphism.