Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Thinking in C++
Prev Contents / Index Next

Passing by const value

You can specify that function arguments are const when passing them by value, such as

void f1(const int i) {
  i++; // Illegal -- compile-time error
} 

but what does this mean? You’re making a promise that the original value of the variable will not be changed by the function f1( ). However, because the argument is passed by value, you immediately make a copy of the original variable, so the promise to the client is implicitly kept.

Inside the function, the const takes on meaning: the argument cannot be changed. So it’s really a tool for the creator of the function, and not the caller.

To avoid confusion to the caller, you can make the argument a const inside the function, rather than in the argument list. You could do this with a pointer, but a nicer syntax is achieved with the reference, a subject that will be fully developed in Chapter 11. Briefly, a reference is like a constant pointer that is automatically dereferenced, so it has the effect of being an alias to an object. To create a reference, you use the & in the definition. So the non-confusing function definition looks like this:

void f2(int ic) {
  const int& i = ic;
  i++;  // Illegal -- compile-time error
} 

Again, you’ll get an error message, but this time the constness of the local object is not part of the function signature; it only has meaning to the implementation of the function and therefore it’s hidden from the client.

Thinking in C++
Prev Contents / Index Next

 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire