Starting from:

$30

COMPLAB-Week 9 Solved

Conversions in C++ 
 

In computer science, type conversion and typecasting are different ways of, implicitly or explicitly, changing an entity of one data type into another. This is done to take advantage of certain features of type hierarchies or type representations. 

 

Explicit type conversion is a type conversion which is explicitly defined within a program (instead of being done by a compiler for implicit type conversion). There are several kinds of explicit conversion: checked, unchecked and bit pattern. In C++, objects can also be downcast: a reference of a base class is cast to one of its derived classes. 

 

Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler. In C++, implicit conversions can be controlled by means of three member functions: (1) single-argument constructors (allows implicit conversion from a particular type to initialize an object; (2) assignment operator (allows implicit conversion from a particular type on assignments); and (3) type-cast operator (allows implicit conversion to a particular type). 

 

 

Task  
 

Download the source code archive from the Course Webpage. Add the downloaded files to your C++ project. Complete the missing implementations, then compile the project and run the program. Make sure that there are no runtime errors. 

 

a)      Test your implementation. If the main() function terminates successfully, then your implementation is correct. Check the execution in Debug mode. 

 

b)      Put breakpoints in all constructors and conversion operators; then run the program in Debug mode. Observe the constructor and conversion operator calls. Explain. 

 

c)      If we leave out the explicit type conversion from the following piece of code, then we shall get an error message: 

 

str1 == (String)"My name is Bond. James Bond."; 

 

What kind of error is that? Try to find the cause of the error. 

 

Decomposition of the program: 

-          String.h: class declaration header; 

-          String.cpp: implementation of class members declared in the header; -  TheUltimateString.cpp: the main program with testing code. 

More products