473,729 Members | 2,355 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How dynamic_cast works internally?

Hi,
I can understand static_cast, reinterpret_cas t 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?
Thanks in advance!

Regards!
Bo

Oct 22 '07 #1
15 12299
On Oct 22, 1:51 pm, Bo Yang <struggl...@gma il.comwrote:
Hi,
I can understand static_cast, reinterpret_cas t 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?
Thanks in advance!

Regards!
Bo
Dynamic cast adjests the offset adress of the perticul type
accordigly .if it does't find the type it will raise the exception (in
case of reference)or it will return null.
Ex:
class base{
};

class base1{
};
class derived : public base1,public base2{
};
deribed temp = new derived;
base2 *p = dynamic_cast<ba se2*temp;

it will adject the prt offset to base2 part of the temp object.

Br,
akshay saidulu

Oct 22 '07 #2
On Oct 22, 4:51 am, Bo Yang <struggl...@gma il.comwrote:
Hi,
I can understand static_cast, reinterpret_cas t 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?
Thanks in advance!

Regards!
Bo
Consider this case:
class A{virtual ~A(){};};
class B:public A{};
A*a=new B;
B*b =dynamic_cast<B *>(a);
Conceptually, it is like this if is were written in C:

void A_dtor(A* ){}
typeinfo A_RTTI(){
static typeinfo
return typeinfo("A");
}//compiler generated
void(*)() A_vtbl[]={A_dtor,A_RTTI };
struct A{
A_vtbl*vptr;
};
A_ctor(){vptr=A _vtbl;}//compiler generated

void B_dtor(B* ){}
typeinfo B_RTTI(){
static typeinfo
return typeinfo("B");
}//compiler generated
void(*)(B*) B_vtbl[]={B_dtor,B_RTTI };
struct B{
B_vtbl*vptr;
};
B_ctor(){vptr=B _vtbl;}//compiler generated

This is what A and B conceptually look like underneath the hood. Now
when dynamic_cast is called, the compiler generates a function
something like

B* Dynamic_Cast(A* a ){
if(*((a->vptr)+1)()==B_ RTTI())
return a;
return 0;
}
>From this, it is easy to extrapolate how this can be extended to work
for references.

You can see the reason now why dynamic_cast only works for types that
have "virtual" somewhere, either a function or inheritance.

Lance

Oct 22 '07 #3
On Oct 22, 2:20 am, Lance Diduck <lancedid...@ny c.rr.comwrote:
On Oct 22, 4:51 am, Bo Yang <struggl...@gma il.comwrote:Hi,
I can understand static_cast, reinterpret_cas t 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?
Thanks in advance!
Regards!
Bo

Consider this case:
class A{virtual ~A(){};};
class B:public A{};
A*a=new B;
B*b =dynamic_cast<B *>(a);. .
B* Dynamic_Cast(A* a ){
if(*((a->vptr)+1)()==B_ RTTI())
return a;
return 0;

}
This implementation might work for typeid - because typeid has to
confirm only that type of the object being tested - matches the
specified type exactly.

A dynamic_cast operator however has to perform a much more complicated
test: whether an object (of unknown thype) is related to another type.
And to make do with a lot less information about the classes involved
than existed in the example above. For example:

struct A
{
virtual ~A() {}
};

bool TestA(void *p)
{
assert( p != NULL);
return dynamic_cast<A* >(p) != NULL;
}

Note that no derived classes of A (if any exist) are visible when this
source file is compiled. So no matter how many large or complex this
program's class hierarchy might be, dynamic_cast<ha s only the "A"
class declaration with which to work here.

So how is dynamic_cast<su pposed to figure out whether p points to a
type that is somehow related to A? Well, given these constraints,
there is only one way to solve this problem. dynamic_cast must search
p's class hierarchy (essentially, discovering its layout as it goes
along) and to continue the search until either a A class is located
with the hierarchy - or there are no other classes left in the
hierarchy that need to be checked.

Greg
Oct 22 '07 #4
ak************@ gmail.com ]:
On Oct 22, 1:51 pm, Bo Yang <struggl...@gma il.comwrote:
>Hi,
I can understand static_cast, reinterpret_cas t 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?
Thanks in advance!

Regards!
Bo

Dynamic cast adjests the offset adress of the perticul type
accordigly .if it does't find the type it will raise the exception (in
case of reference)or it will return null.
Ex:
class base{
};

class base1{
};
class derived : public base1,public base2{
};
deribed temp = new derived;
base2 *p = dynamic_cast<ba se2*temp;

it will adject the prt offset to base2 part of the temp object.
Does it just adject the pointer without any additional check of type?

Regards!
Bo
Oct 22 '07 #5
Lance Diduck:
Consider this case:
class A{virtual ~A(){};};
class B:public A{};
A*a=new B;
B*b =dynamic_cast<B *>(a);
Conceptually, it is like this if is were written in C:

void A_dtor(A* ){}
typeinfo A_RTTI(){
static typeinfo
return typeinfo("A");
}//compiler generated
void(*)() A_vtbl[]={A_dtor,A_RTTI };
struct A{
A_vtbl*vptr;
};
A_ctor(){vptr=A _vtbl;}//compiler generated

void B_dtor(B* ){}
typeinfo B_RTTI(){
static typeinfo
return typeinfo("B");
}//compiler generated
void(*)(B*) B_vtbl[]={B_dtor,B_RTTI };
struct B{
B_vtbl*vptr;
};
B_ctor(){vptr=B _vtbl;}//compiler generated

This is what A and B conceptually look like underneath the hood. Now
when dynamic_cast is called, the compiler generates a function
something like

B* Dynamic_Cast(A* a ){
if(*((a->vptr)+1)()==B_ RTTI())
return a;
return 0;
}
Thank you for your detailed explaination. And you mean all dynamic_cast
use RTTI inside. yes?
>>From this, it is easy to extrapolate how this can be extended to work
for references.

You can see the reason now why dynamic_cast only works for types that
have "virtual" somewhere, either a function or inheritance.
Yes, class with no virtual has no virtual table at all.

Thanks!

Regards!
Bo
Oct 22 '07 #6
Greg Herlihy :
On Oct 22, 2:20 am, Lance Diduck <lancedid...@ny c.rr.comwrote:
>On Oct 22, 4:51 am, Bo Yang <struggl...@gma il.comwrote:Hi,
>> I can understand static_cast, reinterpret_cas t 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?
Thanks in advance!
Regards!
Bo
Consider this case:
class A{virtual ~A(){};};
class B:public A{};
A*a=new B;
B*b =dynamic_cast<B *>(a);. .
>B* Dynamic_Cast(A* a ){
if(*((a->vptr)+1)()==B_ RTTI())
return a;
return 0;

}

This implementation might work for typeid - because typeid has to
confirm only that type of the object being tested - matches the
specified type exactly.

A dynamic_cast operator however has to perform a much more complicated
test: whether an object (of unknown thype) is related to another type.
And to make do with a lot less information about the classes involved
than existed in the example above. For example:

struct A
{
virtual ~A() {}
};

bool TestA(void *p)
{
assert( p != NULL);
return dynamic_cast<A* >(p) != NULL;
}

Note that no derived classes of A (if any exist) are visible when this
source file is compiled. So no matter how many large or complex this
program's class hierarchy might be, dynamic_cast<ha s only the "A"
class declaration with which to work here.

So how is dynamic_cast<su pposed to figure out whether p points to a
type that is somehow related to A? Well, given these constraints,
there is only one way to solve this problem. dynamic_cast must search
p's class hierarchy (essentially, discovering its layout as it goes
along) and to continue the search until either a A class is located
with the hierarchy - or there are no other classes left in the
hierarchy that need to be checked.
So, how C++ go along the classes hierarchy at runtime? RTTI? Is RTTI a
standard of C++? I think RTTI is not a standard part of C++!

Regards!
Bo
Oct 22 '07 #7
On Oct 22, 10:20 am, Lance Diduck <lancedid...@ny c.rr.comwrote:
You can see the reason now why dynamic_cast only works for types that
have "virtual" somewhere, either a function or inheritance.
only for upcast.

downcast must work too regardless to
virtuals:

struct B{};
struct D : B {};
D d;
B & b = dynamic_cast<B& >(d); // OK,
B & b1 = d; // is OK too ;)

DS
Oct 22 '07 #8
On 2007-10-22 09:19:26 -0400, Bo Yang <st********@gma il.comsaid:
>
So, how C++ go along the classes hierarchy at runtime? RTTI? Is RTTI a
standard of C++? I think RTTI is not a standard part of C++!
Well, yes, there is no specification of anything called RTTI in the
language definition. But RTTI is shorthand for the usual implementation
technique for dynamic_cast and for catching exceptions. The compiler
generates type information that's used at runtime to match types as
needed. Hence, RunTime Type Information.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Oct 22 '07 #9
On 2007-10-22 15:19, Bo Yang wrote:
Greg Herlihy :
>On Oct 22, 2:20 am, Lance Diduck <lancedid...@ny c.rr.comwrote:
>>On Oct 22, 4:51 am, Bo Yang <struggl...@gma il.comwrote:Hi,
I can understand static_cast, reinterpret_cas t 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?
Thanks in advance!
Regards!
Bo
Consider this case:
class A{virtual ~A(){};};
class B:public A{};
A*a=new B;
B*b =dynamic_cast<B *>(a);. .
>>B* Dynamic_Cast(A* a ){
if(*((a->vptr)+1)()==B_ RTTI())
return a;
return 0;

}

This implementation might work for typeid - because typeid has to
confirm only that type of the object being tested - matches the
specified type exactly.

A dynamic_cast operator however has to perform a much more complicated
test: whether an object (of unknown thype) is related to another type.
And to make do with a lot less information about the classes involved
than existed in the example above. For example:

struct A
{
virtual ~A() {}
};

bool TestA(void *p)
{
assert( p != NULL);
return dynamic_cast<A* >(p) != NULL;
}

Note that no derived classes of A (if any exist) are visible when this
source file is compiled. So no matter how many large or complex this
program's class hierarchy might be, dynamic_cast<ha s only the "A"
class declaration with which to work here.

So how is dynamic_cast<su pposed to figure out whether p points to a
type that is somehow related to A? Well, given these constraints,
there is only one way to solve this problem. dynamic_cast must search
p's class hierarchy (essentially, discovering its layout as it goes
along) and to continue the search until either a A class is located
with the hierarchy - or there are no other classes left in the
hierarchy that need to be checked.

So, how C++ go along the classes hierarchy at runtime? RTTI? Is RTTI a
standard of C++? I think RTTI is not a standard part of C++!
RTTI is part of the C++ standard, do not confuse it with reflection
though. One way to accomplish this (though I do not think that is how it
is done) would be to add a second pointer (in addition to the vtable)
which points to a type object looking something like this:

class Type
{
char name[];
Type* super[];
Type* derived[];
};

That way typeid could (conceptually) be implemented something like this:

template<typena me T>
type_info typeid(T t)
{
return type_info(t->typePtr->name)
}

And using some simple tree walking algorithms you can find out if a type
is in the same type-hierarchy as another.

--
Erik Wikström
Oct 22 '07 #10

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

Similar topics

3
2497
by: KeithO | last post by:
I am having problems calling dynamic_cast<> on a pointer returned by a dynamically loaded library. The problem seems to be related to the fact that I dynamically load the library because if I link the app with the library it works fine. I am using gcc3.04 compiler on Linux AS2.1 The code works fine with MS VC6.0 and also with SunPro5.3 compilers. The library contains a base class and a derived class and also an extern "C" function that...
8
2596
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 it is the case in the following example: ----------------------------------------------------------- #include <iostream>
5
8727
by: verec | last post by:
I just do not understand this error. Am I misusing dynamic_cast ? What I want to do is to have a single template construct (with no optional argument) so that it works for whatever T I want to use it with. Now, if that T happens to be some subclass of a known base class (object, in this case), I want to perform some extra stuff ... I've read Faq#35, and the most natural solution would have
6
5165
by: xgngli | last post by:
Here I have four classes: RefBook and TextBook, which are inheritated from base class Book; and a class Database, which has an array to store the pointers to those two kinds of books. Now I am writing a member function of Database, print(), which prints the information of all the RefBooks in the array by using dynamic_cast. Below is my code(some implemetations omitted). I don't know why the compiler complains that "cannot dynamic_cast type...
22
4805
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 now at this code: Base *b = new Level2(); Level1 *l1 = dynamic_cast<Level1*>(b); Should dynamic_cast return a valid pointer or 0? I wonder as Visual Studio 2005 returns a valid pointer while g++ 3.4.6 returns 0. Both compilers work as expected...
5
3008
by: mijobee | last post by:
Hello Everyone, I just wanted to check that I'm using dynamic_cast correctly. I have a hierarchy of objects using pure virtual classes and virtual inheritance to implement interfaces. I ran into a problem using C-style casting to an instance of a derived class from its interface type to a variable of its concrete type. I was confused because I thought C-style casts always compiled even if they wouldn't run correctly at runtime. I...
25
3136
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 ``GrandChild'', i.e. types not upper than Child in the above class hierarchy, dynamic_cast<Child*>pBase
18
5283
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 comes down to standard c++ stuff and is not specific to Mac OS X compiler&linker. I have put together a simple test project which can be found at: http://ericgorr.net/LibraryLoading.zip which demonstrates the problem.
0
8917
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8761
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9142
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8148
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6022
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2680
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.