As I am starting with C++ I found the operation below confusing. I got to know about passing by reference and passing by value. But recently I came across functions like this which confused me:
Func1(int &a)
Func2(int *a)
Both of the functions expect the address of a , but when I call Func1 I do that by Func1(a)
and in case of Func2 I call by Func2(&a)
How come Func1 is accepting int a directly while it is expecting the address of a
Answer
Func1(int &a)
// accepts arguments by reference.
// changes to a inside Func1 is reflected in the caller
// a cannot bind to an Rvalue e.g. can't call Func1(5)
// a can never be referring to something that is not a valid object
Func2(int *a)
// accept arguments by value
// change to a inside Func1 not reflected in caller, changes to *a are
// a can bind to an Rvalue e.g. Func1(&localvar)
// a can be NULL. Hence Func2 may need to check if a is NULL
No comments:
Post a Comment