|
-
May 14th, 2012, 03:20 AM
#1
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...
TANUSHREE-AGRAWAL...
-
May 14th, 2012, 03:51 AM
#2
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.
-
May 14th, 2012, 04:00 AM
#3
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]
Last edited by monarch_dodra; May 14th, 2012 at 05:33 AM.
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
-
May 14th, 2012, 05:35 AM
#4
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".
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|