Pass Object As Function Arguments in C++

We can pass objects as arguments in member or non member functions. They can be passed either by value or reference. Pass by value creates another copy of the particular object which is deleted after the function is ended. Pass by reference means that we are passing the same object as a reference so if we do any changes in the object then it will remain permanently.

Here is an example of passing objects in function arguments.

#include<iostream>

using namespace std;

class student{
    string name;
    double marks;
    
    public:
    void details(){
        cout<<"Enter the name of the student ";
        cin>>name;
        cout<<"Enter the marks scored by the student out of 100: ";
        cin>>marks;
    }

    void printdetails(){
        cout<<"The name of the student is: "<<name;
        cout<<"The marks scored by the student is: "<<marks;
    }

    // Passing two objects s1 and s2 of the student class.
    void avgmarks(student s1,student s2){
        cout<<"The avg marks scored is: "<<(s1.marks+s2.marks)/2<<"\n";
    }
};

int main(){
    student s1,s2,s3;

    cout<<"Details of 1st student"<<"\n";
    s1.details();

    cout<<"Details of 2nd student"<<"\n";
    s2.details();

    s3.avgmarks(s1,s2);
}

Output:

Details of 1st student
Enter the name of the student Pulkit
Enter the marks scored by the student out of 100: 88.9
Details of 2nd student
Enter the name of the student Rahul
Enter the marks scored by the student out of 100: 75.4
The avg marks scored is: 82.15

In the above code, we are passing the objects in the avgmarks() function, using the information provided by both the objects the average mark is calculated.

I hope you have understood this blog. Please do comment below if you are still facing any difficulties with this topic.

Leave a Comment

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