←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

Array of Objects, Passing Objects & Constant Member Functions

Study material and explanations for Unit 3

Array of Objects, Passing Objects & Constant Member Functions

1. Array of Objects in C++ (In Simple Words)

Just like you can create an array of 5 integers (int arr[5];), you can also create an Array of Objects (Student classroom[60];).

This allows you to manage data for an entire class of 60 students or 100 bank customers using a simple for loop!

#include <iostream>
#include <string>
using namespace std;

class Student {
    private:
        int rollNo;
        string name;
        float marks;

    public:
        void input() {
            cout << "Enter Roll No, Name, Marks: ";
            cin >> rollNo >> name >> marks;
        }

        void display() const {
            cout << "Roll: " << rollNo << "\tName: " << name << "\tMarks: " << marks << endl;
        }
};

int main() {
    const int SIZE = 3;
    Student classroom[SIZE]; // ARRAY OF 3 OBJECTS!

    cout << "=== Taking Input for " << SIZE << " Students ===" << endl;
    for (int i = 0; i < SIZE; i++) {
        cout << "Student #" << (i + 1) << ":" << endl;
        classroom[i].input(); // Calls input() on classroom[0], classroom[1], etc.
    }

    cout << "\n=== Displaying All Student Records ===" << endl;
    for (int i = 0; i < SIZE; i++) {
        classroom[i].display();
    }

    return 0;
}

2. Passing Objects to Functions

You can pass objects into functions in three ways:

Mechanisms for Passing Objects
1. Pass by Value
void show(Complex c)
Makes a complete duplicate copy of the object in RAM. Changes made inside do not affect the original object. Takes extra memory.
2. Pass by Reference
void show(Complex &c)
Passes an alias (nickname) to the original object. Zero copying! Fast, but the function can modify original data.
3. Pass by Const Reference
void show(const Complex &c)
Best Practice! Passes an alias for super fast speed, but const prevents any modification to the object!

3. Returning Objects from Functions

Just as a function can return an int or float, it can also return a complete object!

ClassName functionName(parameters) {
    ClassName temp;
    // ... calculate values ...
    return temp; // Returns the object
}

Classic Exam Example: Adding Two Complex Numbers

A complex number has a real part and an imaginary part (e.g. 3 + 4i).

#include <iostream>
using namespace std;

class Complex {
    private:
        float real;
        float imag;

    public:
        void set(float r, float i) {
            real = r;
            imag = i;
        }

        void display() const {
            cout << real << " + " << imag << "i" << endl;
        }

        // ACCEPTS AN OBJECT AS ARGUMENT AND RETURNS A NEW OBJECT!
        Complex add(const Complex &c2) const {
            Complex result;
            result.real = this->real + c2.real; // Add real parts
            result.imag = this->imag + c2.imag; // Add imaginary parts
            return result; // Returning the newly created object
        }
};

int main() {
    Complex c1, c2, c3;
    c1.set(3.5f, 2.5f);
    c2.set(1.5f, 4.5f);

    // c1 calls add, passes c2, and stores the returned object in c3
    c3 = c1.add(c2);

    cout << "c1  = "; c1.display();
    cout << "c2  = "; c2.display();
    cout << "Sum = "; c3.display(); // Output: 5 + 7i

    return 0;
}

4. Constant Member Functions (const)

If a function’s job is only to display or check data without changing any variable, you should mark it with the const keyword at the end of its header:

class Account {
    private:
        double balance;

    public:
        // Notice 'const' at the end!
        double getBalance() const {
            // balance = balance + 10; // COMPILER ERROR! Cannot change variables inside a const function!
            return balance;
        }
};

Why is this important?

If you create a constant object (e.g., const Account acc;), that object is only allowed to call constant member functions! If you don’t put const on your getter or display functions, the compiler will refuse to run them on constant objects.


DAVV Exam Preparation Tips

Frequently Asked 5-Mark Questions:

  1. Explain the declaration and memory layout of an Array of Objects in C++.
    Model Answer:
    • Syntax: ClassName arr[size];.
    • Each element in the array is a separate, independent object with its own data members stored side-by-side in RAM.
    • Show how a for loop is used to call input() and display() on arr[i].
  2. What is a constant member function? How do you write it?
    Model Answer:
    • A function that promises not to modify any data members of the class.
    • Declared with const after the parameter parenthesis: void display() const;.
    • const objects can only call const member functions.

Frequently Asked 10-Mark Questions:

  1. Explain how objects are passed as arguments and returned from functions. Write a complete C++ program to add two Time objects (hours, minutes, seconds) handling rollover (60 seconds = 1 minute, 60 minutes = 1 hour).
    Model Answer:
    • Explain Pass by Value vs Pass by Reference for objects.
    • Define a Time class with hours, minutes, and seconds.
    • Write member function Time add(const Time &t2) with rollover:
      • sec = t1.sec + t2.sec; if sec >= 60, min++ and sec %= 60.
      • min = t1.min + t2.min; if min >= 60, hrs++ and min %= 60.
      • hrs = t1.hrs + t2.hrs.
    • Create objects in main(), add them, and print the formatted time.