different between reference and value

D

David

what's the differnce between the following two functions:

void func(int &t){
}

void fun(int t){
}

Can I define both of them as member functions of a class?
 
H

Howard

Artie Gold said:
This one operates the on `t' itself; `t' can be changed.


This one operates on a copy of `t'.

Actually, t is the local variable itself, isnt it?

In the first instance, t is simply a reference to the variable that was
passed to func, and it is actually the variable that was passed to func that
is being operated on inside the function. In the second case, t is a local
copy of the variable that was passed to fun, and operations on it do not
directly affect the variable that was passed to the function, they only
affect the local copy (which is destroyed upon exit from the function).

-Hhoward
 
D

Daniel T.

what's the differnce between the following two functions:

void func(int &t){ t = 5;
}

void fun(int t){ t = 5;
}

int main() {
int a = 0;
int b = 0;
func( a );
assert( a == 5 );
fun( b );
assert( b == 0 );
// see the difference now?
}
Can I define both of them as member functions of a class?

Yes.
 
A

Artie Gold

Howard said:
Actually, t is the local variable itself, isnt it?

In the first instance, t is simply a reference to the variable that was
passed to func, and it is actually the variable that was passed to func that
is being operated on inside the function. In the second case, t is a local
copy of the variable that was passed to fun, and operations on it do not
directly affect the variable that was passed to the function, they only
affect the local copy (which is destroyed upon exit from the function).

-Hhoward
You have expressed it better than I did.

!
--ag
 
J

John Harrison

David said:
what's the differnce between the following two functions:

void func(int &t){
}

void fun(int t){
}

Can I define both of them as member functions of a class?

You mean func not fun?

You can define both as a member of a class, but as soon as you try to call
one you are going to get a ambiguous method call error. I'm assuming that
you meant 'func' not 'fun' as in your previous post.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,175
Messages
2,570,946
Members
47,495
Latest member
Jack William

Latest Threads

Top