473,404 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

What the hell is dynamic_cast for?

Suppose I have the following three classes,

GrandBase <-- Base <-- Child <-- GrandChild

The following cast expression holds true only if pBase points object
of type of ``Child'' or ``GrandChild'', i.e. types not upper than
Child in the above class hierarchy,

dynamic_cast<Child*>pBase

Do I draw this correctly?

Up-casting is safe while down-casting is not. dynamic_cast seems to do
down-casting, so why is dynamic_cast intenting to do the dangerous
work?
Jun 27 '08 #1
25 3094
lovecreatesbea...@gmail.com wrote:
Up-casting is safe while down-casting is not. dynamic_cast seems to do
down-casting, so why is dynamic_cast intenting to do the dangerous
work?
Dynamic casting is intended to do the "dangerous work" more safely.
While a static_cast will simply cast to the derived type regardless of
whether the object is of that type, dynamic cast actually checks that
the object is of that type, and if it isn't, it returns a null pointer.
You can check the returned pointer to see if the cast was successful.
(With static_cast you probably just get a segmentation fault.)

There are situation where downcasting may be unavoidable or the path
of least resistance. Thus it's good to have a tool to make it safer.
Jun 27 '08 #2
lovecreatesbea...@gmail.com wrote:
Suppose I have the following three classes,

GrandBase <-- Base <-- Child <-- GrandChild

The following cast expression holds true only if pBase points object
of type of ``Child'' or ``GrandChild'', i.e. types not upper than
Child in the above class hierarchy,

dynamic_cast<Child*>pBase

Do I draw this correctly?
You missed the parentheses and your class has to be polymorphic (have at
least one virtual function). That's first. And second, the expression

dynamic_cast<Child*>(pBase)

has the type 'Child*', and not "holds true", although it will evaluate
to (Child*)0 if the cast fails.
Up-casting is safe while down-casting is not. dynamic_cast seems to do
down-casting, so why is dynamic_cast intenting to do the dangerous
work?
Not sure what you're asking here. 'dynamic_cast' is allowed to *fail*
and you can either catch the 'std::bad_cast' exception or check the
result (for pointers the result is a null pointer, for references the
exception is thrown).

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #3
On May 28, 12:48 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
lovecreatesbea...@gmail.com wrote:
Suppose I have the following three classes,
GrandBase <-- Base <-- Child <-- GrandChild
The following cast expression holds true only if pBase points object
of type of ``Child'' or ``GrandChild'', i.e. types not upper than
Child in the above class hierarchy,
dynamic_cast<Child*>pBase
Do I draw this correctly?

You missed the parentheses and your class has to be polymorphic (have at
least one virtual function).
Wouldn't that be: "have a vritual destructor"?
Jun 27 '08 #4
On Wed, 28 May 2008 21:07:26 +0200, Fernando Gómez
<fe****************@gmail.comwrote:
On May 28, 12:48 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
>lovecreatesbea...@gmail.com wrote:
Suppose I have the following three classes,
GrandBase <-- Base <-- Child <-- GrandChild
The following cast expression holds true only if pBase points object
of type of ``Child'' or ``GrandChild'', i.e. types not upper than
Child in the above class hierarchy,
dynamic_cast<Child*>pBase
Do I draw this correctly?

You missed the parentheses and your class has to be polymorphic (have at
least one virtual function).

Wouldn't that be: "have a vritual destructor"?
No. He is right.
Jun 27 '08 #5
On May 28, 2:15 pm, David Côme <davidc...@wanadoo.frwrote:
On Wed, 28 May 2008 21:07:26 +0200, Fernando Gómez

<fernando.a.gome...@gmail.comwrote:
On May 28, 12:48 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
lovecreatesbea...@gmail.com wrote:
Suppose I have the following three classes,
GrandBase <-- Base <-- Child <-- GrandChild
The following cast expression holds true only if pBase points object
of type of ``Child'' or ``GrandChild'', i.e. types not upper than
Child in the above class hierarchy,
dynamic_cast<Child*>pBase
Do I draw this correctly?
You missed the parentheses and your class has to be polymorphic (have at
least one virtual function).
Wouldn't that be: "have a vritual destructor"?

No. He is right.
So, can you have a polymorphic class without a virtual destructor?
Jun 27 '08 #6
Fernando Gómez wrote:
On May 28, 2:15 pm, David Côme <davidc...@wanadoo.frwrote:
>On Wed, 28 May 2008 21:07:26 +0200, Fernando Gómez

<fernando.a.gome...@gmail.comwrote:
>>On May 28, 12:48 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
lovecreatesbea...@gmail.com wrote:
Suppose I have the following three classes,
GrandBase <-- Base <-- Child <-- GrandChild
The following cast expression holds true only if pBase points object
of type of ``Child'' or ``GrandChild'', i.e. types not upper than
Child in the above class hierarchy,
dynamic_cast<Child*>pBase
Do I draw this correctly?
You missed the parentheses and your class has to be polymorphic (have at
least one virtual function).
Wouldn't that be: "have a vritual destructor"?
No. He is right.

So, can you have a polymorphic class without a virtual destructor?
You don't need a virtual destructor if you're not planning on
polymorphic destruction.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 27 '08 #7
On 2008-05-28 21:07, Fernando Gómez wrote:
On May 28, 12:48 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
>lovecreatesbea...@gmail.com wrote:
Suppose I have the following three classes,
GrandBase <-- Base <-- Child <-- GrandChild
The following cast expression holds true only if pBase points object
of type of ``Child'' or ``GrandChild'', i.e. types not upper than
Child in the above class hierarchy,
dynamic_cast<Child*>pBase
Do I draw this correctly?

You missed the parentheses and your class has to be polymorphic (have at
least one virtual function).

Wouldn't that be: "have a vritual destructor"?
No, any functions will do. Note that the destructor is a member function
(thought a special one).

--
Erik Wikström
Jun 27 '08 #8
lovecreatesbea...@gmail.com wrote:
Suppose I have the following three classes,

GrandBase <-- Base <-- Child <-- GrandChild

The following cast expression holds true only if pBase points object
of type of ``Child'' or ``GrandChild'', i.e. types not upper than
Child in the above class hierarchy,
In case of multiple inheritance it becomes a bit more complicated. In
fact it returns a non-null pointer to Child if and only if the cast to
Child* is valid. But it may also be a cross cast where Child is neither
derived from Base nor a superclass of it.
dynamic_cast<Child*>pBase

Do I draw this correctly?

Up-casting is safe while down-casting is not. dynamic_cast seems to do
down-casting, so why is dynamic_cast intenting to do the dangerous
work?
dynamic_cast is the C++ way of checking whether a polymorphic object is
of a certain type at runtime. You need this e.g. for type specific
dispatching. I would not call this 'dangerous work'.
Marcel
Jun 27 '08 #9
On May 29, 1:46 am, Juha Nieminen <nos...@thanks.invalidwrote:
lovecreatesbea...@gmail.com wrote:
Up-casting is safe while down-casting is not. dynamic_cast seems to do
down-casting, so why is dynamic_cast intenting to do the dangerous
work?

Dynamic casting is intended to do the "dangerous work" more safely.
While a static_cast will simply cast to the derived type regardless of
whether the object is of that type,
Hi, thank you.

dynamic_cast<T>(pointer) is used with an object pointer, while
static_cast<T>(object) is the implicitly compatible conversion and
works with objects also. Am I right?
dynamic cast actually checks that
the object is of that type, and if it isn't, it returns a null pointer.
You can check the returned pointer to see if the cast was successful.
(With static_cast you probably just get a segmentation fault.)
``is of that type'' means that

dynamic_cast<T>(pointer);

(*pointer) is declared as T or T's derived classes, right?

This cast fails if (*pointer) is declared as T's parent classes or
other un-related classes. Am I right?
There are situation where downcasting may be unavoidable or the path
of least resistance. Thus it's good to have a tool to make it safer.
I read some past posts, some said dynamic_cast indicated flaw in
design :)
Jun 27 '08 #10
On May 29, 1:48 am, Victor Bazarov <v.Abaza...@comAcast.netwrote:
lovecreatesbea...@gmail.com wrote:
Suppose I have the following three classes,
That should be four :) , I added GrandBase but forgot to change the
number.
>
GrandBase <-- Base <-- Child <-- GrandChild
The following cast expression holds true only if pBase points object
of type of ``Child'' or ``GrandChild'', i.e. types not upper than
Child in the above class hierarchy,
dynamic_cast<Child*>pBase
Do I draw this correctly?

You missed the parentheses and your class has to be polymorphic (have at
least one virtual function). That's first. And second, the expression

dynamic_cast<Child*>(pBase)

has the type 'Child*', and not "holds true", although it will evaluate
to (Child*)0 if the cast fails.
Yes, thank you for correcting me.
Jun 27 '08 #11
On May 29, 3:49 am, "lovecreatesbea...@gmail.com"
<lovecreatesbea...@gmail.comwrote:
On May 29, 1:46 am, Juha Nieminen <nos...@thanks.invalidwrote:
lovecreatesbea...@gmail.com wrote:
Up-casting is safe while down-casting is not. dynamic_cast
seems to do down-casting, so why is dynamic_cast intenting
to do the dangerous work?
Dynamic casting is intended to do the "dangerous work" more
safely. While a static_cast will simply cast to the derived
type regardless of whether the object is of that type,
dynamic_cast<T>(pointer) is used with an object pointer, while
static_cast<T>(object) is the implicitly compatible conversion
and works with objects also. Am I right?
Both dynamic_cast and static_cast can be used on pointers and
references. (static_cast can also be used in a lot of other
cases.) When used on pointers or references:

-- static_cast allows moving up or down in the hierarchy (but
not sideways); it also allows converting to or from void*.
When moving down (Base* to Derived*), it makes no
verifications; if the object actually pointed to isn't a
Derived, anything can happen, so it is extremely dangerous
for this sort of casting. Note too that there are some
restrictions on static_cast when virtual base classes are
involved.

-- dynamic_cast only makes sense on pointers or references to
polymorphic types---otherwise, it only allows casting up
(Derived* to Base*), where it has exactly the same semantics
as static_cast. On pointers to polymorphic types, it allows
arbitrary navigation within the hierarchy, including
sideways. It verifies the type: if you dynamic_cast to
Derived*, and the pointer doesn't actually point to a
Derived*, it returns a null pointer (or raises an exception
if it is a reference cast). Except in very exceptional
cases (when the profiler says you must), you should use it
exclusively for down casting.
dynamic cast actually checks that the object is of that
type, and if it isn't, it returns a null pointer. You can
check the returned pointer to see if the cast was
successful. (With static_cast you probably just get a
segmentation fault.)
``is of that type'' means that
dynamic_cast<T>(pointer);
(*pointer) is declared as T or T's derived classes, right?
This cast fails if (*pointer) is declared as T's parent
classes or other un-related classes. Am I right?
I'm not too sure I understand. If pointer is of type Derived*,
dynamic_cast< Base* >( pointer ) always succeeds, of course,
returning a pointer to the Base sub-object of the Derived. If
pointer is of type Base*, dynamic_cast< Derived* >( pointer )
will return a null pointer if the actual object doesn't contain
an unambiguous Derived in its inheritance hierarchy, and a
pointer to the Derived if it does.
There are situation where downcasting may be unavoidable or
the path of least resistance. Thus it's good to have a tool
to make it safer.
I read some past posts, some said dynamic_cast indicated flaw
in design :)
There is no requirement here for someone to be competent before
posting. dynamic_cast is easily abused, but there are cases
where it corresponds to the best design, and there are cases
where it represents the best engineering compromize.

Having a string of dynamic_cast usually is a sign of poor
design.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 27 '08 #12
On May 29, 4:13 pm, James Kanze <james.ka...@gmail.comwrote:
On May 29, 3:49 am, "lovecreatesbea...@gmail.com"

<lovecreatesbea...@gmail.comwrote:
On May 29, 1:46 am, Juha Nieminen <nos...@thanks.invalidwrote:
dynamic cast actually checks that the object is of that
type, and if it isn't, it returns a null pointer. You can
check the returned pointer to see if the cast was
successful. (With static_cast you probably just get a
segmentation fault.)
``is of that type'' means that
dynamic_cast<T>(pointer);
(*pointer) is declared as T or T's derived classes, right?
This cast fails if (*pointer) is declared as T's parent
classes or other un-related classes. Am I right?

I'm not too sure I understand. If pointer is of type Derived*,
dynamic_cast< Base* >( pointer ) always succeeds, of course,
returning a pointer to the Base sub-object of the Derived. If
pointer is of type Base*, dynamic_cast< Derived* >( pointer )
will return a null pointer if the actual object doesn't contain
an unambiguous Derived in its inheritance hierarchy, and a
pointer to the Derived if it does.
Thank you,

I am sorry I didn't express myself clearly.

Suppose there are three classes: Base, Child, GrandChild are
polymorphic classes. Child is derived from Base, and GrandChild from
Child.

I think only the dynamic_cast in ``Case 1'' fails, am I right?

Base *pB, *p;
Child *pC;
GrandChild *pG;

/* pB, pC, pG, proper initialization .. */

// Case 1
p = pB; // legal up-cast
pC = dynamic_cast<Child*>(p); // illegal dynamic-cast

// Case 2
p = pC; // legal up-cast
pC = dynamic_cast<Child*>(p); // legal dynamic-cast

// Case 3
p = pG; // legal up-cast
pC = dynamic_cast<Child*>(p); // legal dynamic-cast
Jun 27 '08 #13
On May 29, 10:16*pm, "lovecreatesbea...@gmail.com"
<lovecreatesbea...@gmail.comwrote:
On May 29, 4:13 pm, James Kanze <james.ka...@gmail.comwrote:


On May 29, 3:49 am, "lovecreatesbea...@gmail.com"
<lovecreatesbea...@gmail.comwrote:
On May 29, 1:46 am, Juha Nieminen <nos...@thanks.invalidwrote:
dynamic cast actually checks that the object is of that
type, and if it isn't, it returns a null pointer. *You can
check the returned pointer to see if the cast was
successful. *(With static_cast you probably just get a
segmentation fault.)
``is of that type'' means that
* * * * dynamic_cast<T>(pointer);
(*pointer) is declared as T or T's derived classes, right?
This cast fails if (*pointer) is declared as T's parent
classes or other un-related classes. Am I right?
I'm not too sure I understand. *If pointer is of type Derived*,
dynamic_cast< Base* >( pointer ) always succeeds, of course,
returning a pointer to the Base sub-object of the Derived. *If
pointer is of type Base*, dynamic_cast< Derived* >( pointer )
will return a null pointer if the actual object doesn't contain
an unambiguous Derived in its inheritance hierarchy, and a
pointer to the Derived if it does.

Thank you,

I am sorry I didn't express myself clearly.

Suppose there are three classes: Base, Child, GrandChild are
polymorphic classes. Child is derived from Base, and GrandChild from
Child.

I think only the dynamic_cast in ``Case 1'' fails, am I right?

* * Base * * * *pB, *p;
* * Child * * **pC;
* * GrandChild *pG;

* * /* pB, pC, pG, proper initialization .. */
or be more specific, here, I exactly menat:

pB = new Base;
pC = new Child;
pG = new GrandChild;
* * // Case 1
* * p = pB; * * * * * * * * * * * // legal up-cast
and of course, no up-cast here
* * pC = dynamic_cast<Child*>(p); // illegal dynamic-cast

* * // Case 2
* * p = pC; * * * * * * * * * * * // legal up-cast
* * pC = dynamic_cast<Child*>(p); // legal dynamic-cast

* * // Case 3
* * p = pG; * * * * * * * * * * * // legal up-cast
* * pC = dynamic_cast<Child*>(p); // legal dynamic-cast
Jun 27 '08 #14
lovecreatesbea...@gmail.com wrote:
I read some past posts, some said dynamic_cast indicated flaw in
design :)
That was probably me and I stand by it. It's a smell. That doesn't
mean it isn't sometimes necessary.
Jun 27 '08 #15
Fernando Gómez wrote:
So, can you have a polymorphic class without a virtual destructor?
Yes, it's just a really bad idea.
Jun 27 '08 #16
On May 29, 5:15 pm, Noah Roberts <u...@example.netwrote:
lovecreatesbea...@gmail.com wrote:
I read some past posts, some said dynamic_cast indicated flaw in
design :)
That was probably me and I stand by it. It's a smell. That
doesn't mean it isn't sometimes necessary.
I think others have been more dogmatic about it than you. It's
potentially a smell, and if I see it being used a lot, I become
suspicious. But there are specific idioms where it is more than
justified; where the alternatives are less clean. And if I see
it in the implementation of one of those idioms, it doesn't
cause me any problems.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #17
On May 29, 4:16 pm, "lovecreatesbea...@gmail.com"
<lovecreatesbea...@gmail.comwrote:
On May 29, 4:13 pm, James Kanze <james.ka...@gmail.comwrote:
On May 29, 3:49 am, "lovecreatesbea...@gmail.com"
<lovecreatesbea...@gmail.comwrote:
On May 29, 1:46 am, Juha Nieminen <nos...@thanks.invalidwrote:
dynamic cast actually checks that the object is of that
type, and if it isn't, it returns a null pointer. You can
check the returned pointer to see if the cast was
successful. (With static_cast you probably just get a
segmentation fault.)
``is of that type'' means that
dynamic_cast<T>(pointer);
(*pointer) is declared as T or T's derived classes, right?
This cast fails if (*pointer) is declared as T's parent
classes or other un-related classes. Am I right?
I'm not too sure I understand. If pointer is of type Derived*,
dynamic_cast< Base* >( pointer ) always succeeds, of course,
returning a pointer to the Base sub-object of the Derived. If
pointer is of type Base*, dynamic_cast< Derived* >( pointer )
will return a null pointer if the actual object doesn't contain
an unambiguous Derived in its inheritance hierarchy, and a
pointer to the Derived if it does.
Suppose there are three classes: Base, Child, GrandChild are
polymorphic classes. Child is derived from Base, and
GrandChild from Child.
Public derivation, or private? And does Base have at least one
virtual function?
I think only the dynamic_cast in ``Case 1'' fails, am I right?
Base *pB, *p;
Child *pC;
GrandChild *pG;
/* pB, pC, pG, proper initialization .. */
// Case 1
p = pB; // legal up-cast
pC = dynamic_cast<Child*>(p); // illegal dynamic-cast
// Case 2
p = pC; // legal up-cast
pC = dynamic_cast<Child*>(p); // legal dynamic-cast
// Case 3
p = pG; // legal up-cast
pC = dynamic_cast<Child*>(p); // legal dynamic-cast
If I suppose public derivation in all cases, and that Base has
at least one virtual function, all of the casts are "legal".
The first will result in a null pointer, and the others to a
pointer to the correct (sub-)object.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #18
On May 29, 5:18 pm, Noah Roberts <u...@example.netwrote:
Fernando Gómez wrote:
So, can you have a polymorphic class without a virtual destructor?
Yes, it's just a really bad idea.
Most of the time. There are exceptions (almost all of which
will have a protected destructor).

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #19
Noah Roberts wrote:
Fernando Gómez wrote:
>So, can you have a polymorphic class without a virtual destructor?

Yes, it's just a really bad idea.
One good rule of thumb I've read is that if you have a polymorphic
class it should either have a virtual public destructor or a non-virtual
protected destructor. In the first case it will be safe to delete a
derived object via a pointer to base. In the second case it will be a
compile-time error.

Joe Gottman
Jun 27 '08 #20
On May 30, 5:09*am, James Kanze <james.ka...@gmail.comwrote:
On May 29, 4:16 pm, "lovecreatesbea...@gmail.com"
<lovecreatesbea...@gmail.comwrote:
On May 29, 4:13 pm, James Kanze <james.ka...@gmail.comwrote:
On May 29, 3:49 am, "lovecreatesbea...@gmail.com"
<lovecreatesbea...@gmail.comwrote:
On May 29, 1:46 am, Juha Nieminen <nos...@thanks.invalidwrote:
dynamic cast actually checks that the object is of that
type, and if it isn't, it returns a null pointer. *You can
check the returned pointer to see if the cast was
successful. *(With static_cast you probably just get a
segmentation fault.)
``is of that type'' means that
* * * * dynamic_cast<T>(pointer);
(*pointer) is declared as T or T's derived classes, right?
This cast fails if (*pointer) is declared as T's parent
classes or other un-related classes. Am I right?
I'm not too sure I understand. *If pointer is of type Derived*,
dynamic_cast< Base* >( pointer ) always succeeds, of course,
returning a pointer to the Base sub-object of the Derived. *If
pointer is of type Base*, dynamic_cast< Derived* >( pointer )
will return a null pointer if the actual object doesn't contain
an unambiguous Derived in its inheritance hierarchy, and a
pointer to the Derived if it does.
Suppose there are three classes: Base, Child, GrandChild are
polymorphic classes. Child is derived from Base, and
GrandChild from Child.

Public derivation, or private? *And does Base have at least one
virtual function?
Yes, I assumed that the Base had a virtual function.

Private derivation doesn't prevent dynamic_cast, am I right?
I think only the dynamic_cast in ``Case 1'' fails, am I right?
* * Base * * * *pB, *p;
* * Child * * **pC;
* * GrandChild *pG;
* * /* pB, pC, pG, proper initialization .. */
* * // Case 1
* * p = pB; * * * * * * * * * * * // legal up-cast
* * pC = dynamic_cast<Child*>(p); // illegal dynamic-cast
* * // Case 2
* * p = pC; * * * * * * * * * * * // legal up-cast
* * pC = dynamic_cast<Child*>(p); // legal dynamic-cast
* * // Case 3
* * p = pG; * * * * * * * * * * * // legal up-cast
* * pC = dynamic_cast<Child*>(p); // legal dynamic-cast

If I suppose public derivation in all cases, and that Base has
at least one virtual function, all of the casts are "legal".
``C++ Primer, 4th'' says in $18.2.1, ``If a dynamic_cast to a pointer
type fails, the result of the dynamic_cast is the value 0.'' If the
dynamic_cast expression evaluates zero, can I regard it as failed?
The first will result in a null pointer, and the others to a
pointer to the correct (sub-)object.
Thanks for reply.
Jun 27 '08 #21
James Kanze wrote:
On May 29, 5:15 pm, Noah Roberts <u...@example.netwrote:
>lovecreatesbea...@gmail.com wrote:
>>I read some past posts, some said dynamic_cast indicated flaw in
design :)
>That was probably me and I stand by it. It's a smell. That
doesn't mean it isn't sometimes necessary.

I think others have been more dogmatic about it than you. It's
potentially a smell, and if I see it being used a lot, I become
suspicious. But there are specific idioms where it is more than
justified; where the alternatives are less clean. And if I see
it in the implementation of one of those idioms, it doesn't
cause me any problems.
*shrug* if you say so...
Jun 27 '08 #22
James Kanze wrote:
On May 30, 4:05 am, "lovecreatesbea...@gmail.com"
<lovecreatesbea...@gmail.comwrote:
>``C++ Primer, 4th'' says in $18.2.1, ``If a dynamic_cast to a
pointer type fails, the result of the dynamic_cast is the
value 0.'' If the dynamic_cast expression evaluates zero, can
I regard it as failed?

Yes. Don't confuse legal/illegal with succeeded/failed. An
illegal dynamic_cast won't compile. But a legal dynamic_cast
can fail at runtime, in which case, it either returns a null
pointer (pointer cast) or throws an exception (reference cast).
Just for sake of completeness, what does dynamic_cast do with an already
null pointer?

p = 0;
pD = dynamic_cast<Derived *>(p); // exception, sigsegv, or null?

--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
Jun 27 '08 #23
Daniel Pitts wrote:
James Kanze wrote:
>On May 30, 4:05 am, "lovecreatesbea...@gmail.com"
<lovecreatesbea...@gmail.comwrote:
>>``C++ Primer, 4th'' says in $18.2.1, ``If a dynamic_cast to a
pointer type fails, the result of the dynamic_cast is the
value 0.'' If the dynamic_cast expression evaluates zero, can
I regard it as failed?

Yes. Don't confuse legal/illegal with succeeded/failed. An
illegal dynamic_cast won't compile. But a legal dynamic_cast
can fail at runtime, in which case, it either returns a null
pointer (pointer cast) or throws an exception (reference cast).
Just for sake of completeness, what does dynamic_cast do with an already
null pointer?

p = 0;
pD = dynamic_cast<Derived *>(p); // exception, sigsegv, or null?
If the argument to dynamic_cast<T*is 0, the cast evaluates to 0. See
[5.2.7/4].
Best

Kai-Uwe Bux
Jun 27 '08 #24
On May 30, 6:48 pm, Daniel Pitts
<newsgroup.spamfil...@virtualinfinity.netwrote:
James Kanze wrote:
On May 30, 4:05 am, "lovecreatesbea...@gmail.com"
<lovecreatesbea...@gmail.comwrote:
``C++ Primer, 4th'' says in $18.2.1, ``If a dynamic_cast to a
pointer type fails, the result of the dynamic_cast is the
value 0.'' If the dynamic_cast expression evaluates zero, can
I regard it as failed?
Yes. Don't confuse legal/illegal with succeeded/failed. An
illegal dynamic_cast won't compile. But a legal dynamic_cast
can fail at runtime, in which case, it either returns a null
pointer (pointer cast) or throws an exception (reference cast).
Just for sake of completeness, what does dynamic_cast do with
an already null pointer?
p = 0;
pD = dynamic_cast<Derived *>(p); // exception, sigsegv, or null?
It's guaranteed to return a null pointer. This is true for all
pointer casts, in fact. (Which means that even static_cast may
require some actual code to be executed.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #25
James Kanze wrote:
>
>Just for sake of completeness, what does dynamic_cast do with
an already null pointer?
>p = 0;
pD = dynamic_cast<Derived *>(p); // exception, sigsegv, or null?

It's guaranteed to return a null pointer. This is true for all
pointer casts, in fact. (Which means that even static_cast may
require some actual code to be executed.)
This can be handy - if you're given a pointer which ought to be to an
object of a derived type, but is a pointer to a base type, you can
dynamic_cast it without first checking for null. If it's null
afterwards either it wasn't the right sort or it was null originally -
either way you head up the error paths after only one test.

Andy
Jun 27 '08 #26

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: steve | last post by:
I am writing for game application. Performance is an issue. Any advise would be appreiciated.
8
by: Thomas Lorenz | last post by:
Hello, first, I didn't find any reference to my question through googling. dynamic_cast uses RTTI to determine if the cast expression is valid. Invalid casts of pointers give a '0'-result. As...
1
by: Steven T. Hatton | last post by:
The result shown below doesn't surprise me now. But it did several months ago when I followed some bad advice and tried to check if I had a live object at the address referenced by a pointer. Can...
19
by: tthunder | last post by:
Hi @all, I've got an interesting problem. These are my classes: ---------------------- class fooBase {
5
by: tthunder | last post by:
Hi @all, Perhaps some of you know my problem, but I had to start a new thread. The old one started to become very very confusing. Here clean code (which compiles well with my BCB 6.0 compiler)....
22
by: Boris | last post by:
I'm porting code from Windows to UNIX and ran into a problem with dynamic_cast. Imagine a class hierarchy with three levels: class Level2 derives from Level1 which derives from Base. If you look...
5
by: sunny | last post by:
hai i am not able to overload a member function of base class in derived calss.what is the wrong thning i am doing here in the following program. # include<iostream> using namespace std; ...
15
by: Grizlyk | last post by:
Hello. Returning to question of manual class type identification, tell me, for ordinary inheritance is C++ garantee that dynamic_cast<Derived*>(Base*) can be implemented similarly to ...
15
by: Bo Yang | last post by:
Hi, I can understand static_cast, reinterpret_cast and const_cast, they all work at compile time. But I can figure out how the C++'s dynamic- cast works? Could you please explain how for me?...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.