Returning by reference from function
struct emp
{
char name[20];
int age;
float sal;
}e1 = {"hello", 24, 2345.67}, e2 = {"hi", 34, 45678.89};
void main()
{
emp &fun();
fun() = e2;
cout << endl << e1.name << endl << e1.age << endl << e1.sal;
}
emp &fun()
{
cout << endl << e1.name << endl << e1.age << endl << e1.sal;
return e1;
}
Query: I am unable to get emp &fun() and fun() = e2...
Re: Returning by reference from function
Please indent and post your code in [code][/code] bbcode tags. Note that:
- You are missing a #include <iostream> and appropriate using declaration/directive.
- void main should be int main
Now, how does this not work? It looks like purely a toy program to see how some aspect of C++ works, but you have not stated anything about what you expect and what actually happened.
Re: Returning by reference from function
Please put your code between [CODE]code tags[/CODE]. Its much easier on people reading you, who want to help you.
Code:
struct emp
{
char name[20];
int age;
float sal;
}e1 = {"hello", 24, 2345.67}, e2 = {"hi", 34, 45678.89};
void main()
{
emp &fun();
fun() = e2;
cout << endl << e1.name << endl << e1.age << endl << e1.sal;
}
emp &fun()
{
cout << endl << e1.name << endl << e1.age << endl << e1.sal;
return e1;
}
To answer your question though, how exactly is
Code:
emp &fun();
fun() = e2;
Supposed to work: fun is a function, and e2 is an object...? [EDIT: Never mind, see next post]
Re: Returning by reference from function
After re-reading your post, I now see what you are trying to do actually.
To add to laserlight: What exactly is not working? You code compiled fine (after adding the headers, and correct "int main()") for me, and ran as was expected.
We'll need more explanation on your part about what is not working, and/or "what you expected to happen" vs "what actually happened".