C++ Objects As Function Arguments

An object can be passed to a function just like we pass a structure to a function. we can pass the object of another class to a function of a different class. We can pass class objects as arguments and return them from a function.

Advertisements

When we want to initialize all data members of an object with another object, we can pass objects and assign the values of a supplied object to the current object. For complex or large projects, we need to use objects as an argument or parameters. So, here’s the question.  

What is an object?

An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is expressed it means an object is created and memory is allocated. 

Declaring Objects: When a class is initialized, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.

Syntax:

ClassName ObjectName;

What is a class?

A class is a template similar to a blueprint that binds the properties and functions of an entity. You can assign all the entities or objects having similar attributes under a single roof, known as a class. These can further implement the core concepts like encapsulation, data hiding, and abstraction. In C++, a class acts as a data type which can have objects or various instances of the class type. 

  • A Class is a user-defined data type that has data members and member functions.
  • Data members includes data variables and member functions are the functions used to manipulate these variables together these data members and member functions define the properties and behavior of the objects in a Class.

Create a class called “MyCycle”:

class MyCycle {       
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

To create an object of MyCycle, specify the class name, and act in accordance by the object name.

To access the class attributes (myNumb and myString), use the dot syntax (.) on the object:

Example #1

Create an object called “myObj” and access the attributes.

class MyCycle {       
  public:             // Access specifier
    int myNumb;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};
int main() {
  MyCycle myObj;  // Create an object of MyCycle
  // Access attributes and set values
  myObj.myNumb = 15; 
  myObj.myString = "Random Info";
  // Print attribute values
  cout << myObj.myNumb << "\n";
  cout << myObj.myString;
  return 0;
}

Output:

15
Random Info

Passing an Object as an argument

The objects of a class can be passed as arguments to member functions as well as non-members functions either by value or by reference. we can pass class objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required.

 A copy of the actual object is created inside the function when an object is passed by value. This copy is destroyed when the function terminates. Moreover, any changes made to the copy of the object inside the function are not reflected in the actual object.

 On the other hand, only a reference to that object (not the entire object) is passed to the function in a pass-by-reference. Thus, the changes made to the object within the function are also reflected in the actual object. No special keyword or header file is required to do so.

Whenever an object of a class is passed to a member function of the same class, its data members can be accessed inside the function using the object name and the dot operator. However, the data members of the calling object can be directly accessed inside the function without using the object name and the dot operator.

To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables.

Syntax: 

function_name(object_name);

Returning Object as argument

The returning object will be stored in another variable Object.

Syntax:

Advertisements
object = return object_name;

Example #2

#include <bits/stdc++.h>
using namespace std;
 
class Test{
public:
    int a;
 
    // This function will take
    // object as arguments and
    // return object
    Test add(Test Ta, Test Tb)
    {
        Test Tc;
        Tc.a = Ta.a + Tb.a;
 
        // returning the object
        return Tc;
    }
};
int main()
{
    Example T1, T2, T3;
 
    // Values are initialized
    // for both objects
    T1.a = 50;
    T2.a = 100;
    T3.a = 0;
 
    cout << "Initial Values \n";
    cout << "Value of object 1: " << T1.a
         << ", \nobject 2: " << T2.a
         << ", \nobject 3: " << T3.a
         << "\n";
 
    // Passing object as an argument
    // to function add()
    T3 = T3.add(T1, T2);
 
    // Changed values after
    // passing object as an argument
    cout << "New values \n";
    cout << "Value of object 1: " << T1.a
         << ", \nobject 2: " << T2.a
         << ", \nobject 3: " << T3.a
         << "\n";
 
    return 0;
}

Output:

Initial Values 
Value of object 1: 50, 
object 2: 100, 
object 3: 0
New values 
Value of object 1: 50, 
object 2: 100, 
object 3: 150

In this example, we can see both the things that are how we can pass the objects as well as return them. When the object T3 calls the add function it passes the other two objects namely T1 & T2 as arguments. Inside the function, another object is declared which calculates the sum of all the three variables and returns it to T3. 


This code and the above code are almost the same, the only difference is that this time the add function returns an object whose value is stored in another object of the same class ‘Test’ T3. Here the value of T1 is displayed by object1, the value of T2 by object2, and the value of T3 by object3.

We can also pass an object as an argument within the member function of the 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 a supplied object to the current object.

For complex or large projects, we need to use objects as an argument or parameters.

Example #3

#include <iostream>
using namespace std;

class Decide
{
	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
	Decide d1;
	Decide d2;
	Decide 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

How do pass objects to functions?

There are four ways of passing objects to functions. Let’s assume you have a class X and want to pass it to a function.

Pass by value

This creates a shallow local copy of the object in the function scope. Things you modify here won’t be reflected in the object passed to it. For example,

Declaration

void fun(X x);
//Calling
X x;
fun(x);

Pass by reference

This passes a reference to the object to the function. Things you modify here will be reflected in the object passed to it. No copy of the object is created. For example,

Declaration

void fun(X &x);
//Calling
X x;
fun(x);

Pass by const reference

This passes a ‘const’ reference to the object to the function. You cannot modify/reassign the object here directly (you can use its methods that do so though). This is useful if you want the function to have only a read-only copy of the object. No copy of the object is created.

Declaration

void fun(X const &x);
//Calling
X x;
fun(x);

Pass by const pointer

This passes a const pointer to the object to the function. You cannot modify/reassign the pointer here.

This is useful if you want the function to have only the address of this object in the pointer. No copy of the object is created.

Declaration

void fun(X const *x);
//Calling
X x;
fun(&x);

Pass by pointer

This passes a pointer to the object to the function. This is similar to passing a reference to the object. No copy of the object is created.

Declaration


void fun(X *x);
//Calling
X x;
fun(&x);

Summary

You have learned about class and objects, how to treat an object as an argument to a function. Not only that , but you also learnt to return the object once the function terminates. It is quite useful to pass objects through function, instead of individual members. But the overhead to send any large object is high when you duplicate the code.

Therefore, we discussed many methods of passing entire object through function with minimum memory. In future articles, we will explore more on this topic.



Advertisements

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Exit mobile version