473,698 Members | 2,445 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 12294
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
2496
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
2592
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
8722
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
5163
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
4802
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
3002
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
3130
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
5282
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
8675
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
9029
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8862
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
7729
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...
1
6521
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5860
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
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3050
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
3
2002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.