All Courses
OOP: ADVANCED OOP TOPICS

Returning Objects from Functions

A function can return an object just like it can return an int or double.

Returning objects is common in OOP.

Example:

Complex add(const Complex& a, const Complex& b);

Complete Example

#include <iostream>
using namespace std;

class Complex {
private:
    double real;
    double imag;

public:
    Complex(double r = 0, double i = 0) : real(r), imag(i) {}

    Complex add(const Complex& other) const {
        return Complex(real + other.real, imag + other.imag);
    }

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

int main() {
    Complex c1(2, 3);
    Complex c2(4, 5);

    Complex c3 = c1.add(c2);
    c3.display();

    return 0;
}

Output:

6 + 8i

What Happens Internally

Older C++ discussions often say returning objects creates temporary objects and copies.

Modern C++ compilers usually optimize this using:

  • Copy elision.
  • Return value optimization.
  • Move semantics.

So returning objects by value is often efficient and natural.

Do Not Return Reference to Local Object

This is dangerous:

// Student& createStudent() {
//     Student s;
//     return s; // wrong: local object dies when function ends
// }

A local object is destroyed when the function ends, so returning a reference to it creates a dangling reference.

Viva Answer

Functions can return objects by value. Modern C++ usually makes this efficient using copy elision, return value optimization, and move semantics. We should not return references or pointers to local objects because they are destroyed when the function ends.

Quick Check

  1. Can a function return an object?
  2. Why is returning a reference to a local object dangerous?
  3. What optimization often makes returning objects efficient?