When Stroustrup talking about C++ as a better C, he mentioned two points:
1. Inline functions in C++ are better than macros in C.
2. Easier pass-by-reference (and the avoidance of the familiar
invalid pointer argument).
Why inline functions are comparative to macros here?
If I have to perform some operation repeatedly, normally I'd write a
function. However, the overhead of calling the function may be high
compared to the actual runing time of the function and I may need to call
it many times - such as looping to read data from a port. Instead of
using a function, which may have unacceptably high overhead, I can use a
macro, which removes the overhead by expanding the macro's code inline.
Problem: macros have no concept of type safety and can have some nasty
side effects. I'd like to avoid these.
Inline functions offer many of the benefits of macros, without most of the
risks. Hence, if you need the speed and you have inline function support,
you'd be better off using it than macros.
Why pass-by-reference is easy in C++?
Because it was designed to be.
In C, to pass a value by reference and to modify the result would require
something like this:
void func( int *ptr ) { *ptr = 3; }
int main() { int x; func( &x ); return 0; }
In C++ you can accomplish the same thing this way:
void func( int& ptr ) { ptr = 3; }
int main() { int x; func(x); return 0; }
Note that you don't need to remember to use the & operator at
point-of-call (in main, in this case) and you don't need to use *ptr to
access the referenced value. In more complex code, this can save some
typing and should avoid cases where you accidentally assign a pointer,
instead of the value:
void func( int *x, int *y ) { x = y; }
int main() { int a, b = 3; func( &x, &y ); return 0; }
-- Presumably, func is supposed to change the value in a to 3 - but
because the coder forgot to use *x and *y, it doesn't. Worse, because
the assignment he made is perfectly valid, no diagnostic is likely to be
emitted.
What does it mean by "avoidance of the familiar invalid pointer
argument"?
Try this:
void func( int *x ) { *x = 3; }
int main()
{
int *a, *b = NULL;
a = malloc(sizeof(int));
b = a;
free(a);
if ( b )
func(b);
return 0;
}
What happens when func(b) is called? Func gets an invalid pointer, and
you have a bug. It is somewhat more difficult to get an invalid reference
in C++ which would duplicate this sort of problem.