ReviseAlgo Logo

Object-Oriented Programming

Classes and Objects

Defining classes and creating objects

Interview: Core OOP concept

Classes and Objects

A class is a user-defined type that bundles data (member variables) and behavior (member functions) into a single unit. Objects are instances of classes — each with their own copy of member variables but sharing member function code. This is the foundation of Object-Oriented Programming.

struct vs class

In C++, struct and class are nearly identical — the only difference is default access: struct members are public by default, class members are private by default. Convention: use struct for plain data aggregates, class for types with encapsulated invariants and behavior.

Member Initialization List

Member initializer lists (Foo(int x) : m_x(x) {}) initialize members directly, before the constructor body runs. This is required for const members and references, and is more efficient than assignment in the body (avoids default-construct + assign pattern).

Interview Corner

Q: What is the difference between shallow copy and deep copy?

A: A shallow copy duplicates the object's memory directly — pointers are copied but not the data they point to (both objects share the same pointed-to data). A deep copy recursively duplicates all owned resources. If a class manages heap memory, the default copy constructor does a shallow copy — you must define a copy constructor and copy assignment operator that perform deep copies (Rule of Three/Five).

Common Pitfalls

  • Forgetting the Rule of Five: If you define a destructor (because the class owns resources), the compiler-generated copy/move operations are often incorrect. Define all five: destructor, copy constructor, copy assignment, move constructor, move assignment.
  • Object slicing: Assigning a derived object to a base object by value — the derived members are "sliced off". Use pointers or references to base class to preserve polymorphism.

Best Practices

  • Use the Rule of Zero when possible — design classes to use RAII members (smart pointers, containers) so the compiler-generated special members work correctly.
  • Prefer member initializer lists over assignment in the constructor body for efficiency and const/reference member support.