C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Wrong usage of static_cast: is output undefined or predicted

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
Alex Vinokur
Guest





PostPosted: Mon Sep 27, 2004 4:55 am    Post subject: Wrong usage of static_cast: is output undefined or predicted Reply with quote




Here is some program in which static_cast is (wrongly) used instead of dynamic_cast.

Is output of the program undefined or predicted?

=========== C++ code : foo.cpp : BEGIN ===========
#include <iostream>
using namespace std;

struct B
{
virtual void foo1 () { cout << "B::foo1" << endl; }
virtual void foo2 () { cout << "B::foo2" << endl; }
};
struct D1 : public B
{
void foo1 () { cout << "D1::foo1" << endl; }
};
struct D2 : public B
{
void foo2 () { cout << "D2::foo2" << endl; }
};

int main ()
{
B* pB = new D1;
// --------------------------
// Of course, here we should use dynamic_cast
D2* pD2 = static_cast // --------------------------

pD2->foo1();
pD2->foo2();

return 0;
}

=========== C++ code : foo.cpp : END =============



=========== Compilation & Run : BEGIN =============

$ g++ --version
g++ (GCC) 3.3.3 (cygwin special)
[---omitted---]

$ g++ -W -Wall foo.cpp
// No errors, no warnings

$ a
D1::foo1
B::foo2


=========== Compilation & Run : END ===============




Back to top
Alf P. Steinbach
Guest





PostPosted: Mon Sep 27, 2004 5:23 am    Post subject: Re: Wrong usage of static_cast: is output undefined or predi Reply with quote



* Alex Vinokur:
Quote:

Here is some program in which static_cast is (wrongly) used instead of dynamic_cast.

Is output of the program undefined or predicted?

UB.

The code will probably work on most compilers since the derived classes
do not add anything to or otherwise change the object memory layout.


Quote:
// --------------------------
// Of course, here we should use dynamic_cast

Just say no to casting.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.