In: Computer Science
Illustrate, by example, how a C++ struct may be passed as a parameter by value or by reference. Also, show how it can be returned from a function. Be thorough in your example and explain your code.
Solution:
Passing a structure as parameter by reference is just same as passing an integer as reference.
In the same way a structure can be returned if it is declared as a return type.
In the example I have created a structure called pointer with 2 attributes x and y.
I used a call by reference function to set the values of the structure point.
I also defined a function midPoint which takes 2 points(structure) as argument and returns the midpoint which is also of type point.
Code:
#include<iostream>
using namespace std;
//Creating a structure for point
struct point
{
float x;
float y;
};
//A fuction that uses call by reference to set values to the point
void setPoint(point &p);
//A function that returns midPoint of 2 points
point midPoint(point a,point b);
//Driver function
int main()
{
//Declaring two points a and b
point a,b;
//Setting values to point a
a.x=0;
b.y=0;
//Call by reference to set values to the point B
setPoint(b);
//Creating a Point for midpoint
point m;
m=midPoint(a,b);
//Printing the details
cout<<"Point a ("<<a.x<<","<<a.y<<")"<<endl;
cout<<"Point b ("<<b.x<<","<<b.y<<")"<<endl;
cout<<"MidPoint ("<<m.x<<","<<m.y<<")"<<endl;
}
void setPoint(point &p)
{
cout<<"Enter value of x and y : ";
cin>>p.x;
cin>>p.y;
}
point midPoint(point a,point b)
{
point m;
m.x=(a.x+b.x)/2;
m.y=(a.y+b.y)/2;
return m;
}
Output: