473,387 Members | 1,569 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,387 software developers and data experts.

dynamic_cast

can someone explain, purely for my information, how
dynamic_cast is implemented using only C++ language
facilities.

I don't mean how to use it, rather what is going on under the
hood.

Thanks

Mark
Jul 22 '05 #1
5 4276

"Mark" <ms******@REMOVETHISBITbtinternet.com> wrote in message
news:cs**********@titan.btinternet.com...
can someone explain, purely for my information, how
dynamic_cast is implemented using only C++ language
facilities.
It's not.

I don't mean how to use it, rather what is going on under the
hood.


That's an implementation detail that can and does vary
among implementations. Since here we only discuss the
language itself, you'll need to ask about this where
your particular compiler is discussed (or perhaps
its vendor's web site).

-Mike
Jul 22 '05 #2
"Mark" <ms******@REMOVETHISBITbtinternet.com> wrote in message
can someone explain, purely for my information, how
dynamic_cast is implemented using only C++ language
facilities.


I think one way to implement it is this: The virtual pointer of a class
points to the virtual table, in the virtual table is a pointer to a
std::type_info object that represents the type info for class, and there is
also a pointer to the virtual table of the parent class.

Suppose you have

Something * s = new MoreDerivedSomething();

Now when you say dynamic_cast<DerivedSomething*>(s), that system gets the
virtual pointer of 's', namely something like s.__vptr. Then check if the
type_info object pointed to in DerivedSomething is the same as the type_info
object pointed to by MoreDerivedSomething. They're not equal. So then
traverse to the virtual table of the parent class, which is the virtual
table of class DerivedSomething and repeat the test. If there is no parent
class then dynamic_cast returns NULL.

This algorithm is O(N) where N is the depth of the hierarchy. Furthermore,
comparing two type_info objects for equality may be O(M) where M is the
length of the class name including namespaces, because there may be multiple
copies of std::type_info objcets for a single class or even multiple copies
of the virtual table, so std::type_info::operator== would have to compare
class names.

This is pretty slow. I'm sure dynamic_cast is required to be a fast
operation. Is it O(1)? How might one achieve this?
Jul 22 '05 #3
"Mike Wahler" <mk******@mkwahler.net> wrote in message news:8nDFd.6054
I don't mean how to use it, rather what is going on under the
hood.


That's an implementation detail that can and does vary
among implementations. Since here we only discuss the
language itself, you'll need to ask about this where
your particular compiler is discussed (or perhaps
its vendor's web site).


General topics about implementation are valid as it might shed light on the
performance hit of using a certain feature, and provide insight for better
future implementations. So one often asks about the cost of iostreams over
printf, vector over array, exceptions over returning ints, and dynamic_cast
over other designs.
Jul 22 '05 #4
> This is pretty slow. I'm sure dynamic_cast is required to be a fast
operation. Is it O(1)? How might one achieve this?


First of all, dynamic_cast usually _is_ relatively slow (though I've
never done enough testing to figure out whether/to what degree its
speed varies with inheritance depth and such).

As far as making things faster, at least a few things are usually
pretty easy: normally, all objects of a particular class (that has
virtual functions) share a single vtable. As such, finding whether two
objects are of the same class requires only comparing their vtable
pointers rather than retrieving and comparing type_info objects.
Pointers can normally be compared in a single operation, reducing this
to O(1) instead of O(N) on the type_info size.

I doubt anybody does a lot to minimize the time taken to traverse the
inheritance tree -- the typical expectation is that inheritance trees
are fairly shallow, and dynamic_casts are fairly rare. If you're
talking about 4 pointer comparisons happening once an hour, nothing you
do with it is going to make any noticeable difference in speed.

If you honestly had a good reason to do so, I'm pretty sure you could
do this with an expected complexity of O(1). Instead of walking the
list of vtable pointers, you'd create a hash-table indexed by the value
of the vtable pointer of the current class. The value it looked up
would be a boolean indicating whether that class could be converted to
the target type for the dynamic_cast.

If you were doing this in a lot of places, you could make it a
two-dimensional lookup, first looking up the table for a given target
type, then looking up the source pointer in that table to find whether
that particular conversion could take place.

As I said, however, I doubt anybody does this -- it would only make
sense if you expected many dynamic_casts, extremely deep inheritance
trees, or both. In fact, you pretty much expect neither.

--
Later,
Jerry.

The universe is a figment of its own imagination.

Jul 22 '05 #5
Mark wrote:
can someone explain, purely for my information, how
dynamic_cast is implemented using only C++ language
facilities.

I don't mean how to use it, rather what is going on under the
hood.

Usually it is *not* implemented with C++ facilities. However all newer
C++ casts keep a templatised syntax, showing the way on how you can
write your own casts (brute force conversions).
Once I had written a cast converting from whatever pointer to another
pointer type, which always points at the beginning of an object, even in
multiple inheritance.
It was in the style:
#include <iostream>
template <class BasePointer, class CurrentPointer>
inline BasePointer base_cast(CurrentPointer cp)
{
return reinterpret_cast<BasePointer>(static_cast<void *>(cp));
}

class A
{};

int main()
{
A a;

unsigned char *p= base_cast<unsigned char *>(&a);
}


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #6

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

Similar topics

13
by: GianGuz | last post by:
Everyone knows about the complex and cpu-expensive procedures taken by dynamic_cast to find the right function call in a virtual classes hierarchy. The question I would to rise is when...
3
by: Axter | last post by:
I'm wondering about the practical use of dynamic_cast in reusable or generic code. I'm currently working on a smart pointer that can be used on vector and other STL containers. See following...
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...
3
by: Ganesh | last post by:
On devx site, I saw following code. It says when a derived class is tried to cast to base type, it looks at the missing vtable and complains if the object is already deleted. I am of the opinion...
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...
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 ...
8
by: pietromas | last post by:
In the example below, why does the dynamic_cast fail (return NULL)? It should be able to cast between sibling classes ... #include <iostream> class A { public: virtual const int get()...
25
by: lovecreatesbea... | last post by:
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...
18
by: Eric | last post by:
Ok...this seems to be treading into some really esoteric areas of c++. I will do my best to explain this issue, but I don't fully understand what is happening myself. I am hoping that the problem...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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,...

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.