Intermediate Business Programming with C++
Copy Constructors & Type Conversion
Copy Constructors
When a class is defined, several constructors are created automatically if they were not defined by the programmer:
-
an implicit constructor (the default constructor)
-
an implicit copy constructor
An implicit constructor is created by the compiler by default if the programmer does not define a constructor. In addition an implicit copy constructor is created by the compiler that copies the contents of one object into the contents of another object at definition time when the contents of one object is assigned to a newly defined object.
The construct of a copy constructor is:
className(const className &anObject)
This would transfer the data of anObject to the object being defined and initialized.. See copy.cpp.
Although the compiler defines an implicit copy constructor, sometimes it is desirable to define an explicit copy constructor. This is particular true if the class has data members that are pointers. If an explicit copy constructor is not defined, then when an object is passed to a function or returned from a function, the data to which the pointer was pointing may be lost.
Type Conversion
In addition to construction and initialization by an object of the class, it is also possible to initialize an object using a constructor with default arguments that do not need to be objects of the class.
By using constructors, it is possible to do type conversion from one class to another. For example, it is possible to create the following constructor:
ClassName(otherClass anObject);
This will convert from an object in OtherClass to an object in ClassName as in the following:
someObject = ClassName(anObject);
For example see: asgnconv.cpp.
Категории