Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

about member variable

Status
Not open for further replies.

jayjay60

Programmer
Jun 19, 2001
97
FR
In my app i declare a pointer as a member variable(double *pTab;). This pointer will be used as a pointer on an array of double. In one of the member function, i want to do some calculation which do affectation like that:
for(i=1;i<=n;i++)
{
*(pTab+i)=Value_i;
}
I don't want that this function return value so i decide it will be type &quot;void&quot;.
And now i want to use this function in another member method. So, if i call the first function, i would like to know if i will be able to get one of specific value of the array.

For example, could i just return the value *(pTab+i2)?

thanks in advance for your help

jayjay
 
you would need to change your function from void to return a double but yes you can do that.

Matt
 
Do you mean that my first function haev to be changed from &quot;voi&quot; to &quot;double&quot;?
 
yes... for example:

// old funciton

void foo()
{
// for loop

}

// new function

double foo()
{
// loop til value found
return *(pTab+i2);

}


the alternative is passing in a argument by reference and setting that to keep the function a void function.

Matt
 
Could you eplain more your last sentence?

gerald
 
What he means is that you could add a new parameter to your function of the form double &x. This is a &quot;pass by reference&quot; parameter, which means that changes to the variable inside the function will be reflected in the originally passed variable. For example:

void myFunc(double &x){
//other code here
for(i=1;i<=n;i++)
{
*(pTab+i)=Value_i;
}
x = *pTab;
}

When this function returns, whatever variable you passed in as the 'x' parameter will contain the value pointed to by pTab at the end of the loop.
 
one remark to &quot;returning by reference&quot;:
it makes a program much more readable if a function returns a value through its type - declaration.
&quot;passing by reference&quot; is OK, but after a few weeks or months you won't know if your function just received a
parameter or also gave something back if it returned some
value by reference.
By the way, you'll see many functions getting their parameters as 'const';

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top