Absolute C++
Walter Savitch
Library nb: B3224
[p.137] The way that you indicate a call-by-reference parameter is to attach the ampersand sign, &, to the end of the type name in the formal parameter list:
void in(A& a)
[p.278] It makes efficiency sense to use a call-by-reference parameter rather than call-by-value parameter for a classi even if the function does not change the parameters:
void isLarger(const A &a, const B &b)
[p.279] If you have a member function thay should not change the value of a calling object, you mark the function with the const modifier; the computer will then issue an error message if your function code inadvertently changes the value of the calling object:
.h
class A
{
void out() const;
}
.cpp
void A::out() const
[p.407] '*' and '&':
v1=0
p1 = &v1; //p1 contains the memory location of v1
*p1 = 42; //the value at memory location p1 = 42 which means that both *p1 and v1 are equal to 42 now
[p.447] If your class member variables involve pointers, dynamic arrays, or any other dynamic data, you should define a copy constructor for the class. Main reason: If you pass a classs type variable to a function as a call-by-value parameter, the function creates a local copy whose dynamic variables point to the same memory locations as the original one:
void show(AClass a)
{
//a is a copy that will be destroyed at the end of this function. If AClass contains dynamic data (data created with new), they will be deleted, resulting in the original parameter having orphaned fields. And if you later (after leaving this function) try to delete those fields, you will get a serious errors that are hard to find.
}
At the end of the function the copy is destroyed. This means that the dynamic variables of the original parameter are also deleted. The solution is to write a copy constructor for AClass which creates a distinct copy that can be safely destroyed:
AClass::AClass(const AClass anObject) //returns a separate but identical copy of anObject. Note that it is call-by-value, not call-by-reference (there is no '&' before anObject). If we made it call-by-reference, we would not be able to create a separate copy, because we would be passing the address of anObject. Really??? Think about this case.
{
capacity = anObject.capacity;
used = anObject.getNumberUsed();
a = new double[capacity]; //dynamic array
for (int i=0; i<used; i++)
{
a[i] = anObject.a[i]
}
}
[p.449] Calling delete twice to delete the same dynamic array (or any other variable created with new) can produce a serious system error that can cause your program to crash.