←Back to Subject
Notes
Notes
Study material and explanations
Diagrams
Diagrams
Visualize concepts easily
Mnemonics
Mnemonics
Tricks to remember faster
One Night Prep
One Night Prep
Short and focused revision
Revision
Revision
Quick summary and key points
Important Questions
Important Questions
Practice most relevant questions
Notes

Arrays Within a Class & Memory Allocation for Objects

Study material and explanations for Unit 3

Arrays Within a Class & Memory Allocation for Objects

1. Arrays as Member Data Within a Class (In Simple Words)

In C++, variables inside a class don’t just have to be single numbers like int rollNo;.

You can also create Arrays inside a class! This is helpful when an object needs to store a collection of related items — like a student’s marks in 5 subjects, or a supermarket shopping cart storing item codes and prices.

#include <iostream>
using namespace std;

const int MAX_ITEMS = 50;

class ShoppingCart {
    private:
        int itemCode[MAX_ITEMS];    // Array to store product IDs
        float itemPrice[MAX_ITEMS]; // Array to store product prices
        int itemCount;              // Keeps track of how many items are added

    public:
        void initialize() { 
            itemCount = 0; 
        }
        
        void addItem(int code, float price) {
            itemCode[itemCount] = code;
            itemPrice[itemCount] = price;
            itemCount++;
        }

        void displayCart() {
            float grandTotal = 0.0;
            cout << "\n--- Supermarket Shopping Cart ---" << endl;
            for (int i = 0; i < itemCount; i++) {
                cout << "Item #" << itemCode[i] << " : Rs. " << itemPrice[i] << endl;
                grandTotal += itemPrice[i];
            }
            cout << "Grand Total: Rs. " << grandTotal << endl;
        }
};

int main() {
    ShoppingCart cart;
    cart.initialize();
    cart.addItem(101, 250.0);
    cart.addItem(102, 120.5);
    cart.addItem(103, 89.0);
    cart.displayCart();

    return 0;
}

2. How Does C++ Allocate Memory for Objects?

A very common myth among students is:
“If I create 1,000 objects of a class, are the functions also copied 1,000 times in RAM?”
NO! C++ is much smarter than that.

Object Memory Architecture in RAM
Code Segment (Loaded ONCE)
Member functions are stored in RAM only once when the program loads. All objects share the exact same function code!
Stack Memory (Separate per Object)
Memory for data variables (like rollNo and marks) is allocated separately for every individual object.
┌─────────────────────────────────────────────────────────────┐
│                 SHARED CODE MEMORY SEGMENT                  │
│                                                             │
│   Member Functions (Stored only 1 time in RAM):             │
│   • void Student::getDetails()                              │
│   • void Student::display()                                 │
└──────────────────────────────┬──────────────────────────────┘
                               │ (Shared by all student objects)
        ┌──────────────────────┴──────────────────────┐
        ▼                                             ▼
┌───────────────────────────┐             ┌───────────────────────────┐
│     OBJECT 1 (s1 in RAM)  │             │     OBJECT 2 (s2 in RAM)  │
├───────────────────────────┤             ├───────────────────────────┤
│ rollNo : 101              │             │ rollNo : 102              │
│ marks  : 85.5             │             │ marks  : 92.0             │
│ (Takes separate 8 bytes)  │             │ (Takes separate 8 bytes)  │
└───────────────────────────┘             └───────────────────────────┘

Why is this design so clever?

  1. Saves Massive RAM: If your class has 20 functions taking 100 KB of compiled code, creating 10,000 objects won’t waste 1 GB of memory! The 100 KB code is stored only once.
  2. How does the shared function know which object called it?
    Whenever you call s1.display(), C++ secretly passes a hidden pointer called the this pointer (&s1). This tells the shared function: “Hey, read the data of s1, not s2!”

DAVV Exam Preparation Tips

Frequently Asked 5-Mark Questions:

  1. How is memory allocated for objects and member functions in C++?
    Model Answer:
    • Member functions are allocated only once in the shared Code Segment of RAM.
    • Data members (variables) get separate memory for every object created on the Stack or Heap.
    • Draw the shared code vs. separate objects diagram.
  2. Write a C++ class with an array member to calculate the average of 5 subjects.
    Model Answer:
    • Class Student with float marks[5].
    • Function to input marks using a for loop, calculate total sum, and print sum / 5.0.

Frequently Asked 10-Mark Questions:

  1. Explain memory allocation for classes and objects in C++. How do multiple objects share member functions without confusing their data? Write a complete inventory/shopping list program.
    Model Answer:
    • Explain memory layout: Code Segment (shared functions) vs. Stack/Heap (separate object variables).
    • Explain the role of the hidden this pointer in distinguishing between calling objects.
    • Write out the complete ShoppingCart class with arrays for item codes and prices, along with add and display functions.