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++

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 ❯

Leave a Reply Cancel reply

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

C++ Tutorial

  • C++ Tutorial
  • First C++ Program
  • C++ Variables
  • C++ Data types
  • C++ Operators

Flow Control

  • C++ If-else
  • C++ Switch Case
  • C++ for loop
  • C++ while loop
  • C++ do-while loop
  • C++ Continue
  • C++ break
  • C++ goto

Functions

  • C++ Functions
  • Default Argument in Function
  • C++ Recursion

Arrays

  • C++ Arrays
  • Multidimensional Arrays
  • C++ Array to Function
  • C++ Strings

Pointers

  • C++ Pointers
  • "this" Pointer

OOPs Concepts

  • C++ OOPs
  • C++ Constructor
  • C++ Destructor
  • C++ Structure
  • Struct and Function
  • C++ Enum
  • C++ Inheritance
  • C++ Polymorphism
  • C++ Function Overloading
  • C++ Function Overriding
  • Function Overloading vs Overriding
  • C++ Virtual Function
  • Encapsulation
  • Abstraction
  • C++ Interfaces
  • Friend Class and Function

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap