Topic 2

Classes and Objects (Memory Allocation: Stack vs. Heap)

3 min read3 questions to test yourself

1Definition

A Class is a user-defined blueprint or data type that specifies properties (data members) and behaviors (member functions). An Object is a self-contained runtime instance of a class that holds actual memory values.

2Simple Explanation

Think of a class as an Architectural Blue-Print for a house. The blueprint itself cannot be lived in, nor does it consume physical bricks or mortar. An object is an actual House constructed from that blueprint. You can build multiple houses (objects) from a single blueprint (class), each with its own painted wall colors or furniture (data values).

3Real-Life Example / Analogy

  • Class: The concept of a Car (defines attributes like color, speed and actions like startCar(), brake()).
  • Object: A specific red BMW parked in your driveway with license plate M PU 2308.

4Diagram / Visual Representation

Instantiation

Instantiation

Class: Car
Data: color, speed, model
Methods: startCar(), changeGear(), brake()

Object 1: BMW
color = Red
speed = 220
model = i8

Object 2: Tesla
color = White
speed = 250
model = Model S

5Working / How It Works

  • Stack Allocation: Created automatically when an object is declared directly (e.g., Student s;). Lifetime is bound to the enclosing function block.
  • Heap Allocation: Created dynamically using the new keyword (e.g., Student* s = new Student();). The pointer variable resides on the stack, while the object instance is allocated in heap memory. Space remains allocated until explicitly freed via delete.

6Types / Components / Characteristics

  • Components of a Class:
    • Data Members: Variables declared inside the class.
    • Member Functions: Functions declared inside the class to manipulate data members.
  • Memory Allocation Comparison:
Feature Stack Allocation (Student s;) Heap Allocation (Student* s = new Student();)
Allocation Mechanism Automatic by compiler Manual via new keyword
Lifetime End of scope / block Until delete is called
Access Velocity Very fast Slower (requires pointer indirection)
Uninitialized Value Garbage value / null object Pointer stores valid heap address

7Solved Examples / Problems

Problem Statement: Demonstrate Stack vs Heap memory allocation for C++ objects.

C++
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
    int id;
    string name;
    Student(int i, string n) : id(i), name(n) {}
    void display() {
        cout << "ID: " << id << ", Name: " << name << endl;
    }
};
int main() {
    // Stack Allocation
    Student s1(1, "John");
    s1.display();
    // Heap Allocation
    Student* s2 = new Student(2, "Alice");
    s2->display();
    delete s2; // Free heap memory
    return 0;
}

Output:

Output
ID: 1, Name: John
ID: 2, Name: Alice

8Advantages, Disadvantages & Applications

  • Advantages:
    • Clear logical separation of state and behavior.
    • Heap objects allow dynamic lifetimes across function calls.
  • Disadvantages:
    • Improper memory management on the heap leads to memory leaks.
    • Dangling pointers if heap memory is deleted prematurely.
  • Applications: Modeling domain entities in e-commerce apps (User, Product, Order).

9Important Points to Remember

  • A class occupies zero byte allocation until instantiated.
  • Size of an empty class object in C++ is 1 byte to ensure distinct memory addresses for unique instances.
  • Accessing heap object members requires the arrow operator (->), while stack objects use the dot operator (.).

10Test Your Understanding

  1. Conceptual Question: Why does an empty class occupy 1 byte of memory in C++?
    Show answer
    C++ requires every instantiated object to have a unique memory address so pointers to objects can be uniquely identified.
  2. MCQ: What happens when an object is instantiated without the new keyword?
    • A) Allocated in Heap Memory
    • B) Allocated in Stack Memory
    • C) Stored in Global Data Segment
    • D) No memory is allocated
    Show answer
    B) Allocated in Stack Memory
  3. Application Question: What is the memory defect present in void foo() { Student* s = new Student(5, "Bob"); }?
    Show answer
    Memory Leak. The function exits without executing delete s;, leaving heap memory allocated but inaccessible.

Finished this topic?

0 of 14 topics read in Object-Oriented Programming

Handwritten notes for the exam

Unit-wise SPPU notes and PYQs for this subject.

Helpful? Share it with your class

Free for everyone, no login needed.

Share topic