Explicit conversions are called casts. Casting is sometimes necessary, but it tends to be overused and can be a major source of errors. In fact, Bjarne Stroupstrup, the creator of C++, is on record recommending that they be used as little as possible.
Because of its roots in the C language, C++ supports the old-style (unsafe) C-style casting (type)expr:
double d=3.14; int i = (int) d;
C++ also supports an alternate constructor-style syntax for casts:
Type t = Type(arglist)
A cast causes a temporary value of the specified type to be created and pushed onto the program stack. If Type is a class, a temporary object is created and initialized by the appropriate conversion constructor. If Type is a native type, Type(arg) is equivalent to (Type) arg. The temporary is kept on the stack just long enough to evaluate the expression it is in. After that, it is destroyed.
For example,
double d = 3.14; Complex c = Complex(d);
Safer Typecasting Using ANSI C++ Typecasts |
Part I: Introduction to C++ and Qt 4
C++ Introduction
Classes
Introduction to Qt
Lists
Functions
Inheritance and Polymorphism
Part II: Higher-Level Programming
Libraries
Introduction to Design Patterns
QObject
Generics and Containers
Qt GUI Widgets
Concurrency
Validation and Regular Expressions
Parsing XML
Meta Objects, Properties, and Reflective Programming
More Design Patterns
Models and Views
Qt SQL Classes
Part III: C++ Language Reference
Types and Expressions
Scope and Storage Class
Statements and Control Structures
Memory Access
Chapter Summary
Inheritance in Detail
Miscellaneous Topics
Part IV: Programming Assignments
MP3 Jukebox Assignments
Part V: Appendices
MP3 Jukebox Assignments
Bibliography
MP3 Jukebox Assignments