Copy Constructors Type Conversion


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:

image from book

 className(const className &anObject) 

image from book

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:

image from book

 ClassName(otherClass anObject); 

image from book

This will convert from an object in OtherClass to an object in ClassName as in the following:

image from book

 someObject = ClassName(anObject); 

image from book

For example see: asgnconv.cpp.




Intermediate Business Programming with C++
Intermediate Business Programming with C++
ISBN: 738453099
EAN: N/A
Year: 2007
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net