: : not quite sure what you are asking -- something along these lines? Where an int is passed to bar() by reference, and bar() passes it by value to foo() ?
: :
: :
: : #include <iostream>
: :
: : using namespace std;
: : void foo(int n)
: : {
: : cout << "foo: oritinal value of n = " << n << endl;
: : n = 1234;
: : cout << "foo: new value of n = " << n << "\n" << endl;
: : }
: :
: : void bar(int& n)
: : {
: : n = 2;
: : cout << "bar: original value of n = " << n << endl;
: : foo(n);
: : cout << "bar: new value of n = " << n << endl;
: : }
: :
: : int main(int argc, char *argv[])
: : {
: : int n = 3;
: : bar(n);
: : system("PAUSE");
: : return EXIT_SUCCESS;
: : }
: :
: :
:
: Thanks!! Yes what you are doing is correct. I want to know in function "void foo(int n)" you are passing it by value does that make copyies even though you are passing the argument by reference in "void bar(int& n)"
: thats what I want to know.
:
:
Well, it's easy enough to test where a copy gets made:
class object
{
public:
object()
{
cout << "Default constructor called." << endl;
}
object(const object& obj)
{
cout << "Copy constructor called." << endl;
}
};
void func2(const object obj) // By value
{
cout << "In function func2." << endl;
}
void func1(const object& obj) // By reference
{
cout << "In function func1, calling function func2." << endl;
func2(obj);
}
int main()
{
object obj;
cout << "In main, calling function func1." << endl;
func1(obj);
return 0;
}
My output:
Default constructor called.
In main, calling function func1.
In function func1, calling function func2.
Copy constructor called.
In function func2.