Lecture 10 (const classes)
Lecture 10 (const classes)
Week # 5
#include <iostream>
using namespace std;
int addition(int a, int b);
Passing by value
int main ()
{
int x=5,y=3,z;
z = addition (x,y);
cout << "The result is " << z;
}
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}
Saqib Rasheed 2
int addition(int &a, int &b);
int main ()
{
Passing by reference
int x=5,y=3,z;
z = addition (x,y);
The keyword const (for constant) precedes the data type of a variable.
It specifies that the value of a variable will not change throughout the
program.
Any attempt to alter the value of a variable defined with this qualifier
will elicit an error message from the compiler.
The qualifier const ensures that your program does not inadvertently
alter a variable that you intended to be a constant, such as the value
of PI in CIRCAREA.
It also reminds anyone reading the listing that the variable is not
intended to change.
The const modifier can apply to other entities besides simple
variables. We’ll learn more about this as we go along
const Function Arguments
We’ve seen that passing an argument by reference can be used
to allow a function to modify a variable in the calling program.
However, there are other reasons to pass by reference.
One is efficiency.
Some variables used for function arguments can be very large
A large structure would be an example. If an argument is large,
passing by reference is more efficient because, behind the scenes,
only an address is really passed, not the entire variable.
Suppose you want to pass an argument by reference for
efficiency, but not only do you want the function not to modify
it, you want a guarantee that the function cannot modify it.
Example
const and Classes
We’ve seen several examples of const used on normal
variables to prevent them from being modified
we saw that const can be used with function arguments to
keep a function from modifying a variable passed to it by
reference.
Now that we know about classes…
we can introduce some other uses of const on member
functions, on member function arguments, and on objects.
These concepts work together to provide some surprising
benefits.
const Objects
In several example programs, we’ve seen that we can
apply const to variables of basic types
};
Save this file as distance.h