![]() |
![]() |
![]() |
![]() |
![]() |
|
C++ programs copy objects using a copy constructor. The C++ compiler always creates a default copy constructor unless you supply one yourself, which you can learn about from C++ handbooks. For the moment, you need to know only that the default copy constructor works by copying the contents of the member variables.
Accordingly, if a member variable contains a pointer, the pointer is copied, but the target of the pointer is not copied. Each railroad-car class object contains a pointer to a serial number, for example. The default copy constructor copies the pointer, but does not copy the chunk of memory reserved for the serial number; that chunk of memory is shared:
Memory reserved for Memory reserved for r,
railroad_car argument the railroad_car parameter
| |
v v
*-----* Copy *-----*
| | -------------> | |
|-----| |-----|
| | | |
|-----| |-----|
| | ---------------* *-------------- | |
|-----| | | *-----*
| | | |
| | |
v v
*---*---*---*---*---*---*---*---*---*
| | | | | | | | | |
*---*---*---*---*---*---*---*---*---*