University of Cambridge >  Engineering Department >  computing help >  Languages >  C++

Passing values in C++

Suppose there's a function f in a class c that's going to be called from another function (main for example). There are many ways that the function f can receive or return integer values. By careful use of const you can make your code safer.

Argument-passing by value or using references

The examples of function f in this section can be called in the following way
int i;
c test_class;
   i=7;
   test_class.f(i);
   cout << "i="   <<i  << endl; 
In C++ references are often used in situations where in the older C language pointers would be used, so if you're already confused by the range of options, it might be best to skip the next section about pointers altogether and go straight onto how to return values.

Argument-passing using pointers

For the examples in this section, function f needs to be called in the following way
void g() {
int i;
c test_class;
   i=7;
   test_class.f(&i);
}
In none of these cases is i copied to a new variable.

Returning values in C++

Suppose there's a function f in a class c that's going to be called from another function. There are many ways that function f can return an integer value

An exercise

const int* c::f(const int * const arg) const;
is a legal declaration. First work out what it means, then write a program which tests to see if your compiler faithfully obeys each of the uses of const.

See also

"C++ Effective Object-Orientated Software Construction", K. Dattatri, Prentice Hall PTR, 2000 has more details.
© Cambridge University Engineering Dept
Information provided by Tim Love (tpl)
Last updated: October 2001