Object as an argument in C++ with example

Learn: How to pass an object within the class member function as an argument in C++ programming language?

As we know that, we can pass any type of arguments within the member function and there are any numbers of arguments.

In C++ programming language, we can also pass an object as an argument within the member function of class.

This is useful, when we want to initialize all data members of an object with another object, we can pass objects and assign the values of supplied object to the current object. For complex or large projects, we need to use objects as an argument or parameter.

Consider the given program:

#include <iostream>
using namespace std;

class Demo {
    int a;

    void set(int x)
        a = x;

    void sum(Demo ob1, Demo ob2)
        a = ob1.a + ob2.a;

    void print()
        cout << "Value of A :  " << a << endl;

int main()
    //object declarations
    Demo d1;
    Demo d2;
    Demo d3;

    //assigning values to the data member of objects

    //passing object d1 and d2
    d3.sum(d1, d2);

    //printing the values

    return 0;


Value of A :  10
Value of A :  20
Value of A :  30

Above example demonstrate the use of object as a parameter. We are passing d1 and d2 objects as arguments to the sum member function and adding the value of data members a of both objects and assigning to the current object’s (that will call the function, which is d3) data member a.

Related Tutorials

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.