Explicit Conversions

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


Introduction to Qt



Inheritance and Polymorphism

Part II: Higher-Level Programming


Introduction to Design Patterns


Generics and Containers

Qt GUI Widgets


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


MP3 Jukebox Assignments

An Introduction to Design Patterns in C++ with Qt 4
An Introduction to Design Patterns in C++ with Qt 4
ISBN: 0131879057
EAN: 2147483647
Year: 2004
Pages: 268

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