×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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.

Object as an argument in C++

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.

Example of object as an argument in C++

Consider the given program:

#include <iostream>
using namespace std;

class Demo {
 private:
  int a;

 public:
  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
  d1.set(10);
  d2.set(20);

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

  // printing the values
  d1.print();
  d2.print();
  d3.print();

  return 0;
}

Output

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

Explanation

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.