{"id":4431,"date":"2014-03-30T10:57:23","date_gmt":"2014-03-30T10:57:23","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/03\/30\/problem-about-static-cast-collection-of-common-programming-errors\/"},"modified":"2014-03-30T10:57:23","modified_gmt":"2014-03-30T10:57:23","slug":"problem-about-static-cast-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/03\/30\/problem-about-static-cast-collection-of-common-programming-errors\/","title":{"rendered":"problem about static-cast-Collection of common programming errors"},"content":{"rendered":"<ul>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/05708634a76195e829ce6dd077e45039?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nSafari<br \/>\nc++ casting polymorphism static-cast<br \/>\nI have a question about c++ cast operators.Suppose you have a class Message and several subclasses: Message1 Message 2 etc.Suppose you have a class Event and also different subclasses of Event: Event 1 Event 2In both cases I can distinguish the type of the subclass from an ID (such as field)class Message { &#8230;. int MessageID; }class Message1 : public Message { \/\/other fields; }class Message2 : public Message { \/\/other fields; }class Event { int eventID; }class Event1 { Message theMessage;Message<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/2faf0c72f6a7f65431e7df489878be24?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nJoseph Garvin<br \/>\nc++ memory templates multiple-inheritance static-cast<br \/>\nIf I have a derived class with multiple bases, each this pointer for each base will be different from that of the derived object&#8217;s this pointer, except for one. Given two types in an inheritance hierarchy, I&#8217;d like to detect at compile time whether they share the same this pointer. Something like this should work, but doesn&#8217;t:BOOST_STATIC_ASSERT(static_cast&lt;Base1*&gt;((Derived *)0xDEADBEEF) == (Derived*)0xDEADBEEF);Because it needs to be an &#8216;integral constant expression&#8217; and only integer cast<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/00afab8556e4ac6e69d7e77db776b5f9?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nuser2341104<br \/>\nc++ design-patterns polymorphism hierarchy static-cast<br \/>\nI have a type heirarchy:class Object { &#8230; };class Node : public Object { &#8230; };class Leaf : public Object { &#8230; };class Something : public Node { &#8230; };class SomethingElse : public Leaf { &#8230; };In other words, absolutely every class inherits Object either directly or indirectly.The constructor for every object is in the following format:ClassType(Object * parent)However, by design only a Node can be a parent, while a Leaf is a terminating node;In the moment, in every constructor I am doing the<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/68fdf71a1519554403013964f2d4380e?s=128&amp;d=identicon&amp;r=PG\" \/><br \/>\ncoelhudo<br \/>\nc++ casting static-cast<br \/>\nWhen I try to use a static_cast to cast a double* to an int*, I get the following error:invalid static_cast from type &#8216;double*&#8217; to type &#8216;int*&#8217;Here is the code:#include &lt;iostream&gt; int main() {double* p = new double(2);int* r;r=static_cast&lt;int*&gt;(p);std::cout &lt;&lt; *r &lt;&lt; std::endl; }I understand that there would be problems converting between a double and an int, but why is there a problem converting between a double* and an int*?<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/2a04086d7656ac97e09c20c4fe4d8266?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nsharptooth<br \/>\nc++ casting crtp static-cast up-casting<br \/>\nI have a plain old CRPT (please don&#8217;t get distracted by access restrictions &#8211; the question is not about them):template&lt;class Derived&gt;class Base {void MethodToOverride(){\/\/ generic stuff here}void ProblematicMethod(){static_cast&lt;Derived*&gt;(this)-&gt;MethodToOverride();} };that is as usual intended to be used like this:class ConcreteDerived : public Base&lt;ConcreteDerived&gt; {void MethodToOverride(){\/\/custom stuff here, then maybeBase::MethodToOverride();}};Now that static_cast bother<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/ba4dd9bf0c9196b1dbaea2fa81995bb7?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nJoachim Pileborg<br \/>\nc++ dynamic-cast static-cast<br \/>\nPlease observe the below code. As far as i know, dynamic_cast is slower than static_cast. Because it evaluates the type at runtime. My doubt here is if we use static_cast with typeid() as below , will it takes same time as dynamic cast ?? Will it be faster than dynamic_cast ?class Shape { public:virtual ~Shape(){} }; class Circle : public Shape{ }; class Square : public Shape{ };Static cast with RTTI: Circle c; Shape* s = &amp;c; \/\/ Upcast: normal and OK\/\/ More explicit but unnecessary: s<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/df125e6d9319554cefa9bd247e2da0eb?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nRoberto<br \/>\nc++ static-cast<br \/>\nI would like to cast a pointer to a member of a derived class to void* and from there to a pointer of the base class, like in the example below: #include &lt;iostream&gt;class Base {public:void function1(){std::cout&lt;&lt;&#8220;1&#8243;&lt;&lt;std::endl;}virtual void function2()=0; };class Derived : public Base {public:virtual void function2(){std::cout&lt;&lt;&#8220;2&#8243;&lt;&lt;std::endl;} };int main() {Derived d;void ptr* = static_cast&lt;void*&gt;(&amp;d);Base* baseptr=static_cast&lt;Base*&gt;(ptr);baseptr-&gt;<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/900b003a0330511b8461543ba16b2721?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nhauzer<br \/>\nc++ overhead static-cast<br \/>\nI have a structure template that takes two types (T and S), and at some point uses a static_cast to convert from one type to the other. It is often the case that T and S are the same type.A simplified example of the setup:template &lt;typename T, typename S = T&gt; struct foo {void bar(T val){\/* &#8230; *\/some_other_function(static_cast&lt;S&gt;(val));\/* &#8230; *\/} };In the case that S is the same class as T, does or can the static_cast introduce extra overhead, or is it a null operation which will al<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/2d563c9aa6378d0668e633e51bfb06c2?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nFihopZz<br \/>\nc++ dynamic-cast static-cast<br \/>\nwhen reading Essential c++ chapter 5.10 Run-time Type identification, I&#8217;ve encountered a problem. Let me introduce a little background first. There are a base class named num_sequence and a class Fibonacci derive from num_sequence. In the base class, there is a virtual function named gen_elems and the derived class has its own definition. The following comes from the book.Fibonacci fib; num_sequence *ps = &amp;fib; ps-&gt;gen_elems(64);We know that the Fibonacci instance of gen_elems() will be i<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/b9cf73fc0a45791674bc5c3670d916b9?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nPetr<br \/>\nc++ runtime overhead static-cast<br \/>\nSee the code below.a) Does, in this case (simple inheritance, no virtual members), the static cast in B::df() have any overhead (whatsoever)? I found some conflicting answers to similar questions, that&#8217;s why I am asking&#8230;b) I was thinking about making const M1 * func private in A and introducing a new private field const M2 * func into B to avoid the cast, but it kind of complicates things up and makes use of smart pointers more difficult. Do you see a better way to avoid the cast?class M1 { pu<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/17486a8ee8ec6952ef351a654c5b65fd?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nAbe Schneider<br \/>\nc++ inheritance polymorphism dynamic-cast static-cast<br \/>\nI&#8217;m pretty sure this is dangerous code. However, I wanted to check to see if anyone had an idea of what exactly would go wrong.Suppose I have this class structure:class A { protected:int a; public:A() { a = 0; } int getA() { return a; }void setA(int v) { a = v; } };class B: public A { protected:int b; public:B() { b = 0; } };And then suppose I want to have a way of automatically extending the class like so:class Base { public:virtual ~Base() {} };template &lt;typename T&gt; class Test: pu<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/e67e16377a02613f5f00206fef390fa0?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nGriffin<br \/>\nc++ pointers if-statement base-class static-cast<br \/>\nHey so I&#8217;m making a serialization function that takes a base class pointer &#8216;Joint&#8217;, extracts the &#8216;type&#8217; of joint descendent it is, and then want to instantiate the correct type of &#8216;definition&#8217; based on whatever kind of &#8216;joint&#8217; the pointer is really pointing too.However i&#8217;m still getting errors about the base class joint not containing functions that a descendent class does have, even though i static_cast the pointer to the correct type. How do i make the complier realize the pointer is being cas<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/1735ab1c8ba4229daa855ec6aad03065?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\njuanchopanza<br \/>\nc++ c++11 shared-ptr static-cast<br \/>\nI am new to C++ style casts, and need help in understanding how the code below works (this is some dummy code I wrote to understand things).#include &lt;iostream&gt; #include &lt;memory&gt;class A { public:A() : a(1) {std::cout &lt;&lt; &#8220;Creating A\\n&#8221;;} ~A() {std::cout &lt;&lt; &#8220;Destroying A\\n&#8221;;} int a; };class B : public A { public:B() : b(2) {std::cout &lt;&lt; &#8220;Creating B\\n&#8221;;} ~B() {std::cout &lt;&lt; &#8220;Destroying B\\n&#8221;;} int b; };int main() {std::shared_ptr&lt;B&gt; objectB(new B());<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/861cfc0de6bf99a544b500eac16229eb?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nMr.C64<br \/>\nc++ pointers casting reinterpret-cast static-cast<br \/>\nConsidering the following code (and the fact that VirtualAlloc() returns a void*):BYTE* pbNext = reinterpret_cast&lt;BYTE*&gt;(VirtualAlloc(NULL, cbAlloc, MEM_COMMIT, PAGE_READWRITE));why is reinterpret_cast chosen instead of static_cast?I used to think that reinterpret_cast is OK for e.g. casting pointers to and from integer types (like e.g. DWORD_PTR), but to cast from a void* to a BYTE*, isn&#8217;t static_cast OK?Are there any (subtle?) differences in this particular case, or are they just both va<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/i.stack.imgur.com\/cEOYD.jpg?s=32&amp;g=1\" \/><br \/>\nKarthik T<br \/>\nc++ casting cocos2d-x static-cast<br \/>\nIn cocos2d-x source code there is some code that handles member function pointers, shown below&#8230;. #define menu_selector(_SELECTOR) (SEL_MenuHandler)(&amp;_SELECTOR) &#8230; typedef void(CCObject::* SEL_MenuHandler )(CCObject *) &#8230;The Idea I gather is to use menu_selector(&lt;MyClass&gt;::&lt;MyFunction&gt;) to get a compatible function pointer. But I believe the use of C style casts allows them to perform unsafe casts, and leading to possible undefined behavior. Am I wrong here? Just now<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/2a04086d7656ac97e09c20c4fe4d8266?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nsharptooth<br \/>\nc++ visual-c++ pointers static-cast<br \/>\nI need to write code for a callback function (it will be called from within ATL, but that&#8217;s not really important):HRESULT callback( void* myObjectVoid ) {if( myObjectVoid == 0 ) {return E_POINTER;}CMyClass* myObject = static_cast&lt;CMyClass*&gt;( myObjectVoid );return myObject-&gt;CallMethod(); }here the void* is guaranteed to be a pointer to CMyClass, so static_cast is legal. My concern is the code must be as portable (to newer versions of Visual C++ at least) as possible. So to be super-paran<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/3189f1e006358ec6c65481b9605cd0e3?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nLightness Races in Orbit<br \/>\nc++ virtual-inheritance downcasting static-cast<br \/>\nConsider the following code:struct Base {}; struct Derived : public virtual Base {};void f() {Base* b = new Derived;Derived* d = static_cast&lt;Derived*&gt;(b); }This is prohibited by the standard ([n3290: 5.2.9\/2]) so the code does not compile, because Derived virtually inherits from Base. Removing the virtual from the inheritance makes the code valid.What&#8217;s the technical reason for this rule to exist?<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/94e2dd813e278309b6281b4a4b7fdddd?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\ncuriousguy<br \/>\nc++ pointers inheritance casting static-cast<br \/>\nI&#8217;m creating a couple of interfaces intended to provide access to a callback functionality. That is, inheriting from interface A allows a class to use callbacks of type one; interface B allows type two. Inheriting from both A and B allows callbacks of both types. The ultimate purpose is that classes A and B will take care of all the dirty work by just inheriting from them.First ProblemHere&#8217;s a small example that should illustrate some of the trouble I&#8217;m having:class A { public:static void AFoo(<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/ab9cb568ed3fe24540e89a242adc95fa?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nKingsIndian<br \/>\nc++ type-conversion static-cast<br \/>\nOK so I tried doing this int b;char x = &#8216;a&#8217;;\/\/Case 1 b = static_cast&lt;int&gt;(x); std::cout&lt;&lt;&#8220;B is : &#8220;&lt;&lt;b&lt;&lt;std::endl;\/\/Case 2 b = *(int*)&amp;x; std::cout&lt;&lt;&#8220;B is changed as :: &#8220;&lt;&lt; b &lt;&lt;std::endl;Now I know that in case 2, first byte of x is reinterpreted to think that it is an integer and the bit pattern is copied into b which gives of some garbage and in case 1 it just converts the value from char to int. Apart from that are there any differences be<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/62d14cf03bbd1f5eb82b8be1cd3c08fc?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nDave Lillethun<br \/>\nc++ pointers casting void-pointers static-cast<br \/>\nI was just reading this thread: Simple c++ pointer castingAnd that got me to thinking why a static_cast between different pointer types is not allowed (except in the cases in which it is) unless you static_cast to a void* as an intermediary step. It seems to me that either both or neither should be allowed. Here is an example:char* cs; unsigned char* ucs;cs = reinterpret_cast&lt;char*&gt;(ucs); \/\/ 1) allowed, of course cs = static_cast&lt;char*&gt;(ucs);<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/b15453cfe4e8b66909382ff570ca3d7f?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nOK.<br \/>\nc++ inheritance casting static-cast<br \/>\nIf we see the below code, fun function converts C&#8217;s object into B&#8217;s object and calls B&#8217; own function. How doesn&#8217;t it give segm fault. I think this will lead to crash. My program is not crashed. Can any one explains why is it working fine.#include&lt;iostream&gt; using namespace std; class A{ public:A() {cout&lt;&lt;&#8220;A&#8217;s Con\\n&#8221;; }~A() {cout&lt;&lt;&#8220;A&#8217;s De\\n&#8221;; } }; class B :public A { public:B() {cout&lt;&lt;&#8220;B&#8217;s Con\\n&#8221;; }~B() {cout&lt;&lt;&#8220;B&#8217;s De\\n&#8221;; }void printb(){cout&lt;&lt;&#8220;B print function\\<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/ee6269873148eeaf5a1cfba501d6eae1?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nMartin B<br \/>\nc++ casting rtti dynamic-cast static-cast<br \/>\nI saw one book on C++ mentioning that navigating inheritance hierarchies using static cast is more efficient than using dynamic cast.Example:#include &lt;iostream&gt; #include &lt;typeinfo&gt;using namespace std;class Shape { public: virtual ~Shape() {}; }; class Circle : public Shape {}; class Square : public Shape {}; class Other {};int main() {Circle c;Shape* s = &amp;c; \/\/ Upcast: normal and OK\/\/ More explicit but unnecessary:s = static_cast&lt;Shape*&gt;(&amp;c);\/\/ (Since upcasting is such<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/c77f27d5fb87727d535dc027d3c080d9?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\ninjoy<br \/>\nc++ static-cast<br \/>\nI&#8217;ve wrote a piece of code, but I am confused with its output:#include &lt;iostream&gt;using namespace std;class B{ public:virtual void foo() {cout &lt;&lt; &#8220;B::foo&#8221; &lt;&lt; endl;} };class D:public B{ public:virtual void foo() {cout &lt;&lt; &#8220;D::foo&#8221; &lt;&lt; endl;}void disp() {cout &lt;&lt; &#8220;D::disp&#8221; &lt;&lt; endl;} };void func(B *pb){D *pd1 = static_cast&lt;D*&gt;(pb);pd1-&gt;foo();pd1-&gt;disp(); }int main(int argc, char *argv[]) {B* pb = new B();func(pb); return 0; }The output is:B::foo D::<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/2a04086d7656ac97e09c20c4fe4d8266?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nsharptooth<br \/>\nc++ casting reinterpret-cast static-cast<br \/>\nThere&#8217;s a set of questions regarding cross-casts (cast from T1* to unrelated T2*), for example this and this. The answer usually goes like this: reinterpret_cast is implementation defined and conversion to void* followed by static_cast is well-defined. Yet I haven&#8217;t see any real examples of what can go wrong when reinterpret_cast is used.What are real-life examples where casting through void* works and reinterpret_cast doesn&#8217;t?<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/215ae780ffe6b94647125ee6bf523d02?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nAschratt<br \/>\nc++ exception casting static-cast<br \/>\nstatic_castwill not throw an exception. But if it does not succeed, it will produce a undefined result. What is the most proper way to check whether the cast succeeded?Will this help?NewType new_typ_obj = static_cast&lt;NewType&gt;(obj); if (new_typ_obj)new_typ_obj.do();<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/59ca992de8dee13baeb893c9c26ee4e0?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\njleahy<br \/>\nc++ embedded reinterpret-cast static-cast<br \/>\nI&#8217;m working on an embedded platform (ARM) and have to be careful when dealing with bit patterns. Let&#8217;s pretend this line is beyond my influence:uint8_t foo = 0xCE; \/\/ 0b11001110Interpreted as unsigned this would be 206. But actually it&#8217;s signed, thus resembling -50. How can I continue using this value as signed?int8_t bar = foo; \/\/ doesn&#8217;t workneither do (resulting in 0x10 or 0x00 for all input values)int8_t bar = static_cast&lt;int8_t&gt;(foo); int8_t bar = reinterpret_cast&amp;<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/0c578ae3e7ea99deced95c91ca5dd728?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nLinuxPenseur<br \/>\nc++ casting static-cast<br \/>\nConsider the following sample code.#include &lt;iostream&gt;using namespace std;class base {public:void func(){cout &lt;&lt; &#8220;base::func()&#8221; &lt;&lt; endl;}};class derived : public base {public:void func(){cout &lt;&lt; &#8220;derived::func()&#8221; &lt;&lt; endl;}};void dummy(base *bptr) {derived *dptr = static_cast&lt;derived*&gt; (bptr);dptr-&gt;func(); }int main() {base bob1;derived dob1;dummy(&amp;dob1); \/\/Line1dummy(&amp;bob1); \/\/Line2 }In Line1, I am passing the address of a derived class object to fu<\/li>\n<\/ul>\n<p>Web site is in building<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Safari c++ casting polymorphism static-cast I have a question about c++ cast operators.Suppose you have a class Message and several subclasses: Message1 Message 2 etc.Suppose you have a class Event and also different subclasses of Event: Event 1 Event 2In both cases I can distinguish the type of the subclass from an ID (such as [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-4431","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/4431","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=4431"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/4431\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=4431"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=4431"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=4431"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}