The important difference is that when passing by const
reference, no new object is created. In the function body, the parameter is effectively an alias for the object passed in.
Because the reference is a const
reference the function body cannot directly change the value of that object. This has a similar property to passing by value where the function body also cannot change the value of the object that was passed in, in this case because the parameter is a copy.
There are crucial differences. If the parameter is a const
reference, but the object passed it was not in fact const
then the value of the object may be changed during the function call itself.
E.g.
int a;
void DoWork(const int &n)
{
a = n * 2; // If n was a reference to a, n will have been doubled
f(); // Might change the value of whatever n refers to
}
int main()
{
DoWork(a);
}
Also if the object passed in was not actually const
then the function could (even if it is ill advised) change its value with a cast.
e.g.
void DoWork(const int &n)
{
const_cast<int&>(n) = 22;
}
This would cause undefined behaviour if the object passed in was actually const
.
When the parameter is passed by const reference, extra costs include dereferencing, worse object locality, fewer opportunities for compile optimizing.
When the parameter is passed by value an extra cost is the need to create a parameter copy. Typically this is only of concern when the object type is large.
const
in C cannot be used to build constant expressions.
For example :
#include <stdio.h>
int main()
{
int i = 2;
const int C = 2;
switch(i)
{
case C : printf("Hello") ;
break;
default : printf("World");
}
}
doesn't work in C because case label does not reduce to an integer constant.
Best Answer
The difference is that for
You point to a class that you cannot change because it is const. But you can modify the myClass pointer (let it point to another class; this don't have any side effects to the caller because it's pointer is copied, it only changes your local the pointer copy) In contrast
Now myClass points to a class that can be modified while you cannot change the parameter.