Function - example there is both a cast (of sorts) and a...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Function-style Casts In C and C++ (and Java(tm)), you can cast one object type to another by usage like: double d = 12.34; int i = (int)d; Casting in this way gets around type system checking. It may introduce problems such as loss of precision, but is useful in some cases. In C++ it's possible to employ a different style of casting using a functional notation: double d = 12.34; int i = int(d); This example achieves the same end as the previous one. The type of a cast using this notation is limited. For example, saying: unsigned long*** p = unsigned long***(0); is invalid, and would need to be replaced by: typedef unsigned long*** T; T p = T(0); or by the old style: unsigned long*** p = (unsigned long***)0; Casting using functional notation is closely tied in with constructor calls. For example: class A { public: A(); A(int); }; void f() { A a; a = A(37); } causes an A object local to f() to be created via the default constructor. Then this object is assigned the result of constructing an A object with 37 as its argument. In this
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: example there is both a cast (of sorts) and a constructor call. If we want to split hairs a perhaps more appropriate technical name for this style of casting is "explicit type conversion". It is also possible have usage like: void f() { int i; i = int(); } If this example used a class type with a default constructor, then the constructor would be called both for the declaration and the assignment. But for a fundamental type, a call like int() results in a zero value of the given type. In other words, i gets the value 0. The reason for this feature is to support generality when templates are used. There may be a template such as: template <class T> class A { void f() { T t = T(); } }; and it's desirable that the template work with any sort of type argument. Note that there are also casts of the form "static_cast<T>" and so on, which we will discuss in a future issue....
View Full Document

This note was uploaded on 02/27/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University-West Lafayette.

Page1 / 2

Function - example there is both a cast (of sorts) and a...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online