10.4. Variables, pointers, and references¶
C++ follows the C conventions regarding which variables are instances of a data type and which variables are pointers to data. Pointers, arrays, pointer arithmetic, the dereference operator, and the address-of operator behave the same in C++ as C.
C++ uses pointer notation when
a reference to data is needed rather than an instance of the data
type. In the following code, b is an instance of the data and the
expression b = a;
implies that the assignment operator actually
makes a copy of the class, [2] which works in C++, but not in C.
class holder { public: int value; }; holder a; // note, explicit allocation not required. holder b; a.value = 7; b = a; // assignment is a copy operation. a.value = 12; cout << "b value " << b.value << endl; // prints 7
If we want b to be a pointer to a ….
class holder { public: int value; }; holder a; // note, explicit allocation not required. holder *b; // b is a pointer a.value = 7; b = &a; // pointer assignment. a.value = 12; cout << "b value " << b->value << endl; // prints 12
Note also, that in the above example, if we wanted a to also be a pointer, we could have said…
holder *a, *b; a = new holder(); // form of dynamic memory allocation a->value = 7; b = a; // pointer assignment ...
10.4.1. C++ References¶
C++ does provide the notion of a reference. References in C++ basically just hide the pointer notation, but are implemented using pointers. Once a reference assignment is made, it can not be changed.
A reference is declared in C++ using the & character.
class holder { public: int value; }; holder a; // note, explicit allocation not required. holder & b = a; // b is a reference (like a pointer) a.value = 7; a.value = 12; cout << "b value " << b.value << endl; // prints 12
References are often in association with operator overloading. For example, here we overload the [] operator for the purpose of manipulating characters of a string.
class string { ... char & operator [] (unsigned int index) { return buffer[index]; } ... private: char * buffer; }; ... string text = "name"; text[0] = 'f'; // change name to fame
The purpose of the statement text[0]
is to come up with a
dereferenced pointer to a character so an ansignment can change the
text. Although the syntax used to accomplish this is fairly
concise, it is also some what missleading. The syntax is as if
text is a simple char array, which is not true.
I would prefer to do the same thing as follows. The following code does the same thing in a fairly simple way, but does not hide or misrepresent what we are asking the computer to do.
class string { ... char *get_char_ptr (unsigned int index) { return (buffer + index); } ... private: char * buffer; }; ... string text = "name"; *(text.get_char_ptr(0))= 'f'; // change name to fame
[2] | The copy operation is tied to the assignment operator by operator overloading, which is discused later. |