Jump to content
  • Advertisement
Sign in to follow this  
icecubeflower

struct members by reference

This topic is 3732 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
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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!