473,847 Members | 1,851 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dynamic_cast for down casting from base to concrete type

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
modified the code to use dynamic_cast which seems correct, compiles and
runs but have found some contradictory information about its use so I
wanted to confirm I'm using it correctly. The code below illustrates
my problem. Thanks for your help.
#include <stdio.h>

class IObject
{
public:
virtual bool Equals(IObject *object) = 0;

};

class IList : public virtual IObject
{
public:
virtual IObject *Get(int index) = 0;
};

class Object : public virtual IObject
{
public:
virtual bool Equals(IObject *object) {
return this == object;
}
};

class ArrayList : public Object, public virtual IList
{
public:
virtual IObject *Get(int index) {
return this; // Just return something
}
};

class String : public Object { };
int main(int argc, char *argv[])
{
IList *list = new ArrayList();
IObject *obj = new String();
String *str = (String *)obj;
// This works: String *str = dynamic_cast<St ring *>(obj);
printf("str %s null.\n\0", str == 0 ? "is" : "is not");

}

Example.cpp: In function 'int main(int, char**)':
Example.cpp:39: error: cannot convert from base 'IObject' to derived
type 'String' via virtual base 'IObject'

Oct 29 '06 #1
5 3012
In article <11************ *********@m7g20 00cwm.googlegro ups.com>,
"mijobee" <mi*****@mijobe e.comwrote:
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
modified the code to use dynamic_cast which seems correct, compiles and
runs but have found some contradictory information about its use so I
wanted to confirm I'm using it correctly. The code below illustrates
my problem. Thanks for your help.
#include <stdio.h>
#include <cstdio>
#include "String.h" // wherever this class is...
>
class IObject
{
public:
virtual ~IObject() { }
virtual bool Equals(IObject *object) = 0;

};

class IList : public virtual IObject
{
public:
virtual IObject *Get(int index) = 0;
};

class Object : public virtual IObject
{
public:
virtual bool Equals(IObject *object) {
return this == object;
}
};

class ArrayList : public Object, public virtual IList
{
public:
virtual IObject *Get(int index) {
return this; // Just return something
}
};

class String : public Object { };
int main(int argc, char *argv[])
{
IList *list = new ArrayList();
IObject *obj = new String();
String *str = (String *)obj;
The above doesn't work because Object derives from IObject virtually.
// This works: String *str = dynamic_cast<St ring *>(obj);
printf("str %s null.\n\0", str == 0 ? "is" : "is not");
delete list;
delete obj;
}

Example.cpp: In function 'int main(int, char**)':
Example.cpp:39: error: cannot convert from base 'IObject' to derived
type 'String' via virtual base 'IObject'
Frankly, this isn't Java. I would dump the Object class and keep things
by value when possible. But then I would use std::string instead of
inventing my own string class...

--
To send me email, put "sheltie" in the subject.
Oct 29 '06 #2

Standard answer to dynamic cast ... If you have to use it, you're
almost certainly doing somthing wrong - that said, let's move on.

mijobee wrote:
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
modified the code to use dynamic_cast which seems correct, compiles and
runs but have found some contradictory information about its use so I
wanted to confirm I'm using it correctly. The code below illustrates
my problem. Thanks for your help.
#include <stdio.h>

class IObject
{
public:
virtual bool Equals(IObject *object) = 0;

};

class IList : public virtual IObject
{
public:
virtual IObject *Get(int index) = 0;
};

class Object : public virtual IObject
{
public:
virtual bool Equals(IObject *object) {
return this == object;
}
};

class ArrayList : public Object, public virtual IList
{
public:
virtual IObject *Get(int index) {
return this; // Just return something
}
};

class String : public Object { };
int main(int argc, char *argv[])
{
IList *list = new ArrayList();
IObject *obj = new String();
String *str = (String *)obj;
// This works: String *str = dynamic_cast<St ring *>(obj);
printf("str %s null.\n\0", str == 0 ? "is" : "is not");

}

Example.cpp: In function 'int main(int, char**)':
Example.cpp:39: error: cannot convert from base 'IObject' to derived
type 'String' via virtual base 'IObject'
I don't in particular understand why the C style cast fails, but it is a
good thing IMHO because it's time to give up on it. It's too error
prone. If I were you I would look at the compiler docs to see if the
compiler has a flag to permit such things.
String *str = dynamic_cast<St ring *>(obj);

if ( str != 0 )
{
// obj IS a pointer to String
// go ahead an use str
} else {
// obj IS NOT at pointer to String
// so other thing
}
Oct 29 '06 #3
Gianni Mariani wrote:
Standard answer to dynamic cast ... If you have to use it, you're
almost certainly doing somthing wrong - that said, let's move on.
True, but with one notable exception that is relevant to the original
question.

A dynamic_cast should always be used when casting from a derived class
to a virtual base. Using a static_cast (which is always a safe
operation when casting from a derived class to a non-virtual base)
leads to undefined behavior when casting to a virtual base class.

Greg

Oct 29 '06 #4
Greg wrote:
Gianni Mariani wrote:
>Standard answer to dynamic cast ... If you have to use it, you're
almost certainly doing somthing wrong - that said, let's move on.

True, but with one notable exception that is relevant to the original
question.

A dynamic_cast should always be used when casting from a derived class
to a virtual base. Using a static_cast (which is always a safe
operation when casting from a derived class to a non-virtual base)
leads to undefined behavior when casting to a virtual base class.
C and V please. If I understand you:

struct A {};
struct B : virtual A {}

int main()
{
B *b = new B;
/* You claim that this is undefined behavior? */
A * a = static_cast<A*> (b)
}

I haven't found anything that would suggest that.

--
Clark S. Cox III
cl*******@gmail .com
Oct 29 '06 #5

Clark S. Cox III wrote:
Greg wrote:
Gianni Mariani wrote:
Standard answer to dynamic cast ... If you have to use it, you're
almost certainly doing somthing wrong - that said, let's move on.
True, but with one notable exception that is relevant to the original
question.

A dynamic_cast should always be used when casting from a derived class
to a virtual base. Using a static_cast (which is always a safe
operation when casting from a derived class to a non-virtual base)
leads to undefined behavior when casting to a virtual base class.

C and V please. If I understand you:

struct A {};
struct B : virtual A {}

int main()
{
B *b = new B;
/* You claim that this is undefined behavior? */
A * a = static_cast<A*> (b)
}

I haven't found anything that would suggest that.
Actually, I had the direction of the cast reversed. The corrected
example would be::

struct A {};
struct B : virtual A {}

int main()
{
A *a = new B;

B * b = static_cast<B*> (a); // undefined
}

If A were an ordinary base class of B then the static_cast would be OK.

Greg

Oct 29 '06 #6

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

Similar topics

18
2845
by: Andreas Sch. | last post by:
Hello, I had been quite suprised by the following little program: ---- cut ---- #include "iostream.h" class base {
17
3368
by: steve | last post by:
I am writing for game application. Performance is an issue. Any advise would be appreiciated.
4
27649
by: Maurice Termeer | last post by:
Hi, suppose i've got this: class a { public: int n; }; class b : public a { public: };
2
1508
by: hijinks | last post by:
I am trying to port a python program into c++ to more learn about c++... so i am trying to do a MVC design.. so here is my events class Event { public: Event() {} Event(string text) { this->name = text; } virtual string getName() { return this->name; }
5
2463
by: Leslaw Bieniasz | last post by:
Hello, I have the following OOP design problem. I have a base class designed as an element of a list, let's say: class A { public: // some stuff
22
4818
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...
15
2829
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 return (Base*->type_fild >= Derived_typeid)? Base*: 0;
25
3145
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
5291
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
9730
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
10647
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...
1
10706
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10338
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
9481
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
7056
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
5719
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
5910
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4527
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

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.