BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Pass and return Object from a function in C++

Last Updated: September 12, 2017 by Chaitanya Singh | Filed Under: Learn C++

In this tutorial we will see how to pass an object to a function as an argument and how to return an object from a function.

Pass object to a function

An object can be passed to a function just like we pass structure to a function. Here in class A we have a function disp() in which we are passing the object of class A. Similarly we can pass the object of another class to a function of different class.

#include <iostream>
using namespace std;
class A {
public:
   int n=100;
   char ch='A';
   void disp(A a){
      cout<<a.n<<endl;
      cout<<a.ch<<endl;
   }
};
int main() {
   A obj;
   obj.disp(obj);
   return 0;
}

Output:

100
A

Return object from a function

In this example we have two functions, the function input() returns the Student object and disp() takes Student object as an argument.

#include <iostream>
using namespace std;
class Student {
public:
   int stuId;
   int stuAge;
   string stuName;
   /* In this function we are returning the
    * Student object.
    */
   Student input(int n, int a, string s){
      Student obj;
      obj.stuId = n;
      obj.stuAge = a;
      obj.stuName = s;
      return obj;
   }
   /* In this function we are passing object
    * as an argument.
    */
   void disp(Student obj){
      cout<<"Name: "<<obj.stuName<<endl;
      cout<<"Id: "<<obj.stuId<<endl;
      cout<<"Age: "<<obj.stuAge<<endl;
   }
};
int main() {
   Student s;
   s = s.input(1001, 29, "Negan");
   s.disp(s);
   return 0;
}

Output:

Name: Negan
Id: 1001
Age: 29
❮ PreviousNext ❯

Top Related Articles:

  1. Structures in C++
  2. Data Types in C++
  3. Function Overriding in C++
  4. Interfaces in C++: Abstract Class
  5. Function Overloading – Call of Overloaded Function is ambiguous

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap