struct members by reference

Started by
3 comments, last by icecubeflower 15 years, 8 months ago
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?
Advertisement
If you wrote the code why didn't you just test it? Yes you do this.
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.
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.
Nice icon. Out of this World is one of the best games I ever played.

This topic is closed to new replies.

Advertisement