C++ Object and Function

C++ Object and Function 

In this post, you will learn how to pass an object to the function and how to object return from the function in the c++ language.


How to pass the object to the function?


Passing the object is just like passing the variable or structure to the function. Following is the example of how to pass an object to the function.


#include<iostream>

using namespace std;


class myhouse{ //define the myhouse class

int numberofroom; //attributes

int numberoffloor;

public:

myhouse(int room, int floor){ //constructor

numberofroom=room;

numberoffloor=floor;

}


void display(myhouse &obj) //passing the object in the function

{

cout<<obj.numberoffloor<<endl;

cout<<obj.numberofroom<<endl;

}

void getdata(){ //function for accessing data

cout<<numberoffloor<<endl;                                //display number of floor

cout<<numberofroom<<endl;                                //display number of room

}


};



int main()

{

myhouse obj(5,10); //create first object

myhouse obj2(20,30);

obj.display(obj2); //passing the object into the function


return 0;

}

Here, the display function accepts one parameter as an object of the class myhouse.Take care of one thing object of the class. The class argument and passing object belong to the same class.


How to return an object from the function?

Returning the object from the function is just as simple as returning the normal variable. Only use the class name as return data type as a primitive data type.
            
object-function

Example


#include<iostream>
using namespace std;

class myhouse{ //define the myhouse class


public:
int numberofroom;
int numberfloor;
myhouse(int room, int floor){ //constructor
numberofroom=room;
numberfloor=floor;
}

void display(myhouse &obj) //passing the object in the function
{
cout<<"number of floor ="<<obj.numberfloor<<endl;
cout<<" number of room ="<<obj.numberofroom<<endl;
}

void getdata(){ //function for accessing data
cout<<numberfloor<<endl;
cout<<numberofroom<<endl;
}

};


myhouse getobject(int num,int num1)
{
myhouse objectt(num,num1);
objectt.numberfloor=num;
objectt.numberofroom=num1;
return objectt;
}
int main()
{
myhouse obj(5,10); //create first object
myhouse obj2(20,30); //create second object
obj2=getobject(80,90); //get new object
obj.display(obj2); //call the display function;

return 0;
}

In this example,getobject function is used to returning object and get the object. the return data type is myhouse and two parameters pass through it. Return data type is user-defined data type makes function able to return the object of that class's object.

Please write the comment,if you find anything incorrect and any problem in the above topic or you want to share more information about the above topic.

Comments

Popular posts from this blog

how to cout in cpp

Flutter layout

Diferrence between flutter and react native