English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Functions that pass and return objects

In this article, you will learn how to pass and return objects in C ++In programming, objects can be passed to a function and returned from the function.

In C ++In programming,Objects can be passed to a function in a way similar to structures.

How to pass an object to a function?

Example1: Pass objects to the function

C ++The program adds two complex numbers by passing objects to the function.

#include <iostream>
using namespace std;
class Complex
{
    private:
       int real;
       int imag;
    public:
       Complex(): real(0), imag(0) { }
       void readData()
        {
           cout << "Please enter the real and imaginary numbers:" << endl;
           cin >> real >> imag;
        }
        void addComplexNumbers(Complex comp1, Complex comp2)
        {
           // real represents the object c3actual data, because it uses code c3.add(c1, c2); You can call this function;
            real = comp1.real+comp2.real;
             // imag represents the object c3the imag data of, because it uses code c3.add(c1, c2); You can call this function
            imag = comp1.imag+comp2.imag;
        }
        void displaySum()
        {
            cout << "Sum = " << real << ""+" << imag << "i";
        }
};
int main()
{
    Complex c1,c2,c3;
    c1.readData();
    c2.readData();
    c3.addComplexNumbers(c1, c2);
    c3.displaySum();
    return 0;
}

Output result

Please enter the real and imaginary numbers:
2
4
Please enter the real and imaginary numbers:
-3
4
Sum = -1+8i

How to return an object from a function?

In C ++In programming,  The way objects can be returned from a function is similar to structures.

Example2: Pass and return objects from the function

In this program, the sum of complex numbers (objects) will be returned to the main() function and displayed.

#include <iostream>
using namespace std;
class Complex
{
    private:
       int real;
       int imag;
    public:
       Complex(): real(0), imag(0) { }
       void readData()
        {
           cout << "Please enter the real and imaginary numbers:" << endl;
           cin >> real >> imag;
        }
        Complex addComplexNumbers(Complex comp2)
        {
            Complex temp;
            //real represents the object c3actual data, because it uses code c3.add(c1, c2); You can call this function;
            temp.real = real+comp2.real;
            //imag represents the object c3the imag data of, because it uses code c3.add(c1, c2); You can call this function
            temp.imag = imag+comp2.imag;
            return temp;
        }
        void displayData()
        {
            cout << "Sum = " << real << "";+" << imag << "i";
        }
};
int main()
{
    Complex c1, c2, c3;
    c1.readData();
    c2.readData();
    c3 = c1.addComplexNumbers(c2);
    c3.displayData();
    
    return 0;
}