Passing and Returning of Objects To and From Functions

Submitted by: 
Language: 

Passing and Returning of objects to/from Functions

In this part you will learn:
1. How to pass objects to a function
2. Arrow operator
3. Syntax of passing an object
4. How to return an object from a function
5. Syntax of returning an object
6. Program with object passing and returning
7. Output

Passing an Object to Function
Just like built-in data types like int, char, float , user-defined class’s object can be passed to a function in c++. A little difference is that in case of classes, function have access not only to the functions that are passed but also to the caller object of the function. This caller object’s members can be either directly accessed in the function or by using “this” pointer.
“this” pointer is a special type of pointer which points to the caller object of the function in which we are currently in. To access members of the caller object using “this” pointer we use arrow operator (->). Just like we use dot operator for accessing members of object of a class, we use arrow operator to access the members of an object being pointed by a pointer. We will see its use in the program at the end of this topic.
Let us come back to the passing of objects, just like normal data types. The objects are passed in two ways.
• Pass by value
• Pass by reference
In pass by value, a separate copy of the object is created using copy constructor. As discussed earlier, it is one of the cases when copy constructor is called. So if we have pointers as the members of object, it is a good programming practice to pass object by value and perform deep copy in the constructor. This is because the function may perform some changes like deletion of member pointer of passed object which will cause loss of data and later when the destructor of the object will be called, it will try to delete memory which is already been deleted.
Note: If there is no constructor available and we an object by value, bit by bit copy would be done, which will work fine in case of member variables other than pointers.
The other way of passing an object is, pass by reference. In pass by reference, there is no copy created but the reference of original object is passed in the function. Which means that any changes performed in the function on that object will have its effect on the passed object too.
Syntax
return_type function_name(Class_Name &(as requirement) Object_Name1, Class_Name Object_Name2, Class_Name Object_Name2 )
{
//function operations
}
We can pass ass many parameters to a function as we want.
Returning an Object from a Function
We can return an object from a function by simply writing the return_type as the name of the class of which that object is made of. But there is a little issue in it. As we know that for objects, as soon as their scope ends, their respective destructors are called. While after calling the return function, the scope of the object ends, its destructor is called before reaching back to the calling point of the function we are in. So the object which we want to return gets deleted even before reaching to the caller of the function.
Again this is the case when copy constructor is called for that object. i.e. whenever an object is returned. Its copy constructor is called which copies the data before the calling of destructor. In this way our object returned safely.
Syntax
Class_name_of_object_we_want_to_return function_name()
{
//function operations
return Object_we_want_to_return;
}

Program with Object passing and returning
In this example I will illustrate how static data member work, for this purpose, let us take example of sets.
Basic Step:

  1. #include<iostream>
  2. #include<conio.h>
  3. using namespace std;

These two are the most common and basic lines of a c++ program. The first one iostream is used to grant us most of the basic functions of C++ like Input and Output functions. The second one conio.h means console input output, the black screen we see is the console. Using namespace std; provides us an ease of using all the library functions without specifying that this function belongs to standard library. Without including it, we have to write ‘std’ with all the built-in functions.
Class

  1. class fraction
  2. {
  3. private: //access specifier
  4. int num;
  5. int denom;
  6. public:
  7. void getfraction(){
  8. cout << "Fraction is: " << num << "/" << denom;
  9. }
  10. void setfraction(){
  11. cout << "Enter numerator: ";
  12. cin >> num;
  13. cout << "Enter denominator: ";
  14. cin >> denom;
  15. }
  16. fraction addfraction(fraction f){
  17. fraction sum;
  18. sum.num = (this->num*f.denom) + (this->denom*f.num);
  19. sum.denom = this->denom*f.denom;
  20.  
  21. return sum;
  22. }
  23.  
  24. };

In the above class, I have defined three functions for fractions namely getfraction, setfraction and addfraction. The first two are generally setters and getters, they are getting and printing the value of fraction together. The third function which explains the actual working of object passing and returning is the addfraction function.
In addfraction function, I am passing the value of an object ‘f’ of class fraction. This fraction ‘f’ along with the caller object will add up in a third fraction created inside the function. This new created fraction will be returned to the calling point of the function addfraction.
Let us take a look at main function.
Main

  1. int main()
  2. {
  3. fraction f1; //initializing a variable f1 of type fraction
  4. fraction f2; //initializing a variable f2 of type fraction
  5. f1.setfraction();
  6. f2.setfraction();
  7.  
  8. fraction f3;
  9. f3 = f1.addfraction(f2);
  10.  
  11. f3.getfraction();
  12.  
  13. system("pause");
  14. }

In the main function, first two objects of class fraction are created namely f1 and f2. Then their values are being assigned by the user in setfraction function. Then I am declaring another object of class fraction with name f3. Next instruction is the most important part.
“f3 = f1.addfraction(f2);” means that, the function addfraction will be called by f1, which means that the “this” pointer will be pointing to the object f1. f2 fraction will be passed in the function as a parameter. After all the computation in addfuntion. The sum will be returned as an object of class fraction which will be assigned to the object f3.
Then the program will print the sum using getfraction function.

Output
picture viewer


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.