The Following in my book:
"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
// Ex7_09.cpp
// Initializing an object with an object of the same class
#include <iostream>
using std::cout;
using std::endl;
class CBox // Class definition at global scope
{
public:
// Constructor definition
explicit CBox(double lv = 1.0, double bv = 1.0, double hv = 1.0)
{
cout << endl << "Constructor called.";
m_Length = lv; // Set values of
m_Width = bv; // data members
m_Height = hv;
}
// Function to calculate the volume of a box
double Volume()
{
return m_Length*m_Width*m_Height;
}
private:
double m_Length; // Length of a box in inches
double m_Width; // Width of a box in inches
double m_Height; // Height of a box in inches
};
int main()
{
CBox box1(78.0, 24.0, 18.0);
CBox box2 = box1; // Initialize box2 with box1
cout << endl
<< "box1 volume = " << box1.Volume()
<< endl
<< "box2 volume = " << box2.Volume();
cout << endl;
return 0;
}
|
This example produces the following output:
Constructor called.
box1 volume = 33696
box2 volume = 33696 |
How It Works
The program is working as you would want, with both boxes having the same volume. However, as you can see from the output, our constructor was called only once for the creation of box1. The question is, how was box2 created? The mechanism is similar to the one that you experienced when you had no constructor defined and the compiler supplied a default constructor to allow an object to be created. In this instance, the compiler generates a default version of what is referred to as a copy constructor.
A copy constructor does exactly what we’re doing here — it creates an object of a class by initializing it with the values of the data members of an existing object of the same type. The default version of the copy constructor creates a new object by copying the existing object, member by member.
This is fine for simple classes such as CBox, but for many classes — classes that have pointers or arrays as members, for example — it won’t work properly. Indeed, with such classes the default copy constructor can create serious errors in your program. In these cases, you must create your own copy constructor. This
requires a special approach that you’ll look into more fully toward the end of this chapter and again in the next chapter.
"
I have a question about this sentence in the last paragraph:
"This is fine for simple classes such as CBox, but for many classes — classes that have pointers or arrays as members, for example — it won’t work properly."
Why wont it work properly for arrays or pointers as members? Can someone please shed some light on this for me?