Sign in to follow this  
icecubeflower

struct members by reference

Recommended Posts

What if you have this struct:
struct Speckeeper
{
   Iceint icespec[3];  //not all three are always used
   string name;
};

Now say you have this function:
void stupidfunction(string &strfun, ifstream &infile)
{
   int ix;

   strfun="Data/";
   ix=5;
   while(strfun[ix-1]!=' '&&ix<20)
   {
      strfun+=infile.get();
      ix+=1;
   }
   strfun.resize(ix-1);
}

Could you go like this?:
Speckeeper skulls;
ifstream dumbfile;

stupidfunction(skulls.name, dumbfile);

What I'm pointing out is the the string is pass by reference in that function. So does that mean after stupidfunction goes out of scope the value of skulls.name will be changed?

Share this post


Link to post
Share on other sites
Yes, you can pass a struct or class member into a function taking a parameter by reference the same as any other variable. Equally, you can pass the address of a struct or class member to a function expecting a pointer.


void f(std::string &s)
{
s="hello";
}

void g(int *i)
{
(*i)=23;
}

struct test
{
std::string text;
int value;
};

int main()
{
test t;

f(t.text);
g(&(t.value));

std::cout << t.text << "\n" << t.value << "\n";
}


The above will output:

hello
23

much as you would expect.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this