www.digitalmars.com         C & C++   DMDScript  

D - cast syntax

reply "Sean L. Palmer" <spalmer iname.com> writes:
Is the cast keyword required for casts, or not?

What follows is from the D Programming Language, expressions section.  It
isn't very clear what exactly the D syntax actually is, especially since the
very last thing is an example of why D doesn't need instanceof, which does
not use the cast keyword:

Sean

Cast Expressions
In C and C++, cast expressions are of the form:
	(type) unaryexpression

There is an ambiguity in the grammar, however. Consider:
		(foo) -  p;

Is this a cast of a dereference of negated p to type foo, or is it p being
subtracted from foo? This cannot be resolved without looking up foo in the
symbol table to see if it is a type or a variable. But D's design goal is to
have the syntax be context free - it needs to be able to parse the syntax
without reference to the symbol table. So, in order to distinguish a cast
from a parenthesized subexpression, a different syntax is necessary.
C++ does this by introducing:

	dynamic_cast(expression)

which is ugly and clumsy to type. D introduces the cast keyword:
	cast(foo) -p;	cast (-p) to type foo
	(foo) - p;	subtract p from foo

cast has the nice characteristic that it is easy to do a textual search for
it, and takes some of the burden off of the relentlessly overloaded ()
operator.
D differs from C/C++ in another aspect of casts. Any casting of a class
reference to a derived class reference is done with a runtime check to make
sure it really is a proper downcast. This means that it is equivalent to the
behavior of the dynamic_cast operator in C++.

	class A { ... }
	class B : A { ... }

	void test(A a, B b)
	{
	     B bx = a;		error, need cast
	     B bx = cast(B) a;	bx is null if a is not a B
	     A ax = b;		no cast needed
	     A ax = cast(A) b;	no runtime check needed for upcast
	}

D does not have a Java style instanceof operator, because the cast operator
performs the same function:
	Java:
		if (a instanceof B)
	D:
		if ((B) a)
Nov 19 2001
parent "Walter" <walter digitalmars.com> writes:
"Sean L. Palmer" <spalmer iname.com> wrote in message
news:9tage9$1f0k$1 digitaldaemon.com...
 Is the cast keyword required for casts, or not?

It originally was, then I took it out, now I'm considering putting it back in.
Nov 19 2001