• Advertisement
Sign in to follow this  

struct members by reference

This topic is 3499 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
I don't have access to my computer. I'm on my sister's windows box and I'm reading a C++ book but it's really hard to read.

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
Sign in to follow this  

  • Advertisement