One-Argument Constructor and Operator Function
We studied that a single-argument constructor or an operator function could be used for conversion of objects of different classes. A large range of classes as class libraries are available with the compiler; however, they are linked with the main program. Their source code is invisible to us. Only object of these classes can be used. The user cannot change the in-built classes. The problem occurs when a programmer attempts conversion from object of class declared by him/her to type of in-built class. This problem can be avoided by defining conversion routine in the user-defined class. The conversion routine may be single-argument constructor or an operator function. It depends on whether the object is a source or destination. Table describes conversion type and place of routine to be defined, followed by description.
- In case both the source and destination objects are of user-defined type, the conversion routine can be carried out using operator function in source class or using constructor in destination class.
- If the user-defined object is a destination object, the conversion routine should be carried out using single-argument constructor in the destination objectâ€™s class.
- In case the user-defined object is a source object, the conversion routine should be carried out using an operator function in the source objectâ€™s class.
Defining multiple conversion routines puts the complier in an uncertain condition. The compiler fails to select appropriate conversion routines. For example, if one argument constructor is present in destination class and operator function in source class, the complier cannot select appropriate routines. Hence, while defining conversion routines, follow the conditions given in Table.