problem about static-cast-Collection of common programming errors


  • 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 field)class Message { …. int MessageID; }class Message1 : public Message { //other fields; }class Message2 : public Message { //other fields; }class Event { int eventID; }class Event1 { Message theMessage;Message

  • Joseph Garvin
    c++ memory templates multiple-inheritance static-cast
    If I have a derived class with multiple bases, each this pointer for each base will be different from that of the derived object’s this pointer, except for one. Given two types in an inheritance hierarchy, I’d like to detect at compile time whether they share the same this pointer. Something like this should work, but doesn’t:BOOST_STATIC_ASSERT(static_cast<Base1*>((Derived *)0xDEADBEEF) == (Derived*)0xDEADBEEF);Because it needs to be an ‘integral constant expression’ and only integer cast

  • user2341104
    c++ design-patterns polymorphism hierarchy static-cast
    I have a type heirarchy:class Object { … };class Node : public Object { … };class Leaf : public Object { … };class Something : public Node { … };class SomethingElse : public Leaf { … };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

  • coelhudo
    c++ casting static-cast
    When I try to use a static_cast to cast a double* to an int*, I get the following error:invalid static_cast from type ‘double*’ to type ‘int*’Here is the code:#include <iostream> int main() {double* p = new double(2);int* r;r=static_cast<int*>(p);std::cout << *r << 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*?

  • sharptooth
    c++ casting crtp static-cast up-casting
    I have a plain old CRPT (please don’t get distracted by access restrictions – the question is not about them):template<class Derived>class Base {void MethodToOverride(){// generic stuff here}void ProblematicMethod(){static_cast<Derived*>(this)->MethodToOverride();} };that is as usual intended to be used like this:class ConcreteDerived : public Base<ConcreteDerived> {void MethodToOverride(){//custom stuff here, then maybeBase::MethodToOverride();}};Now that static_cast bother

  • Joachim Pileborg
    c++ dynamic-cast static-cast
    Please 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 = &c; // Upcast: normal and OK// More explicit but unnecessary: s

  • Roberto
    c++ static-cast
    I 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 <iostream>class Base {public:void function1(){std::cout<<“1″<<std::endl;}virtual void function2()=0; };class Derived : public Base {public:virtual void function2(){std::cout<<“2″<<std::endl;} };int main() {Derived d;void ptr* = static_cast<void*>(&d);Base* baseptr=static_cast<Base*>(ptr);baseptr->

  • hauzer
    c++ overhead static-cast
    I 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 <typename T, typename S = T> struct foo {void bar(T val){/* … */some_other_function(static_cast<S>(val));/* … */} };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

  • FihopZz
    c++ dynamic-cast static-cast
    when reading Essential c++ chapter 5.10 Run-time Type identification, I’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 = &fib; ps->gen_elems(64);We know that the Fibonacci instance of gen_elems() will be i

  • Petr
    c++ runtime overhead static-cast
    See 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’s why I am asking…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

  • Abe Schneider
    c++ inheritance polymorphism dynamic-cast static-cast
    I’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 <typename T> class Test: pu

  • Griffin
    c++ pointers if-statement base-class static-cast
    Hey so I’m making a serialization function that takes a base class pointer ‘Joint’, extracts the ‘type’ of joint descendent it is, and then want to instantiate the correct type of ‘definition’ based on whatever kind of ‘joint’ the pointer is really pointing too.However i’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

  • juanchopanza
    c++ c++11 shared-ptr static-cast
    I 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 <iostream> #include <memory>class A { public:A() : a(1) {std::cout << “Creating A\n”;} ~A() {std::cout << “Destroying A\n”;} int a; };class B : public A { public:B() : b(2) {std::cout << “Creating B\n”;} ~B() {std::cout << “Destroying B\n”;} int b; };int main() {std::shared_ptr<B> objectB(new B());

  • Mr.C64
    c++ pointers casting reinterpret-cast static-cast
    Considering the following code (and the fact that VirtualAlloc() returns a void*):BYTE* pbNext = reinterpret_cast<BYTE*>(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’t static_cast OK?Are there any (subtle?) differences in this particular case, or are they just both va

  • Karthik T
    c++ casting cocos2d-x static-cast
    In cocos2d-x source code there is some code that handles member function pointers, shown below…. #define menu_selector(_SELECTOR) (SEL_MenuHandler)(&_SELECTOR) … typedef void(CCObject::* SEL_MenuHandler )(CCObject *) …The Idea I gather is to use menu_selector(<MyClass>::<MyFunction>) 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

  • sharptooth
    c++ visual-c++ pointers static-cast
    I need to write code for a callback function (it will be called from within ATL, but that’s not really important):HRESULT callback( void* myObjectVoid ) {if( myObjectVoid == 0 ) {return E_POINTER;}CMyClass* myObject = static_cast<CMyClass*>( myObjectVoid );return myObject->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

  • Lightness Races in Orbit
    c++ virtual-inheritance downcasting static-cast
    Consider the following code:struct Base {}; struct Derived : public virtual Base {};void f() {Base* b = new Derived;Derived* d = static_cast<Derived*>(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’s the technical reason for this rule to exist?

  • curiousguy
    c++ pointers inheritance casting static-cast
    I’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’s a small example that should illustrate some of the trouble I’m having:class A { public:static void AFoo(

  • KingsIndian
    c++ type-conversion static-cast
    OK so I tried doing this int b;char x = ‘a’;//Case 1 b = static_cast<int>(x); std::cout<<“B is : “<<b<<std::endl;//Case 2 b = *(int*)&x; std::cout<<“B is changed as :: “<< b <<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

  • Dave Lillethun
    c++ pointers casting void-pointers static-cast
    I 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<char*>(ucs); // 1) allowed, of course cs = static_cast<char*>(ucs);

  • OK.
    c++ inheritance casting static-cast
    If we see the below code, fun function converts C’s object into B’s object and calls B’ own function. How doesn’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<iostream> using namespace std; class A{ public:A() {cout<<“A’s Con\n”; }~A() {cout<<“A’s De\n”; } }; class B :public A { public:B() {cout<<“B’s Con\n”; }~B() {cout<<“B’s De\n”; }void printb(){cout<<“B print function\

  • Martin B
    c++ casting rtti dynamic-cast static-cast
    I saw one book on C++ mentioning that navigating inheritance hierarchies using static cast is more efficient than using dynamic cast.Example:#include <iostream> #include <typeinfo>using namespace std;class Shape { public: virtual ~Shape() {}; }; class Circle : public Shape {}; class Square : public Shape {}; class Other {};int main() {Circle c;Shape* s = &c; // Upcast: normal and OK// More explicit but unnecessary:s = static_cast<Shape*>(&c);// (Since upcasting is such

  • injoy
    c++ static-cast
    I’ve wrote a piece of code, but I am confused with its output:#include <iostream>using namespace std;class B{ public:virtual void foo() {cout << “B::foo” << endl;} };class D:public B{ public:virtual void foo() {cout << “D::foo” << endl;}void disp() {cout << “D::disp” << endl;} };void func(B *pb){D *pd1 = static_cast<D*>(pb);pd1->foo();pd1->disp(); }int main(int argc, char *argv[]) {B* pb = new B();func(pb); return 0; }The output is:B::foo D::

  • sharptooth
    c++ casting reinterpret-cast static-cast
    There’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’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’t?

  • Aschratt
    c++ exception casting static-cast
    static_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<NewType>(obj); if (new_typ_obj)new_typ_obj.do();

  • jleahy
    c++ embedded reinterpret-cast static-cast
    I’m working on an embedded platform (ARM) and have to be careful when dealing with bit patterns. Let’s pretend this line is beyond my influence:uint8_t foo = 0xCE; // 0b11001110Interpreted as unsigned this would be 206. But actually it’s signed, thus resembling -50. How can I continue using this value as signed?int8_t bar = foo; // doesn’t workneither do (resulting in 0x10 or 0x00 for all input values)int8_t bar = static_cast<int8_t>(foo); int8_t bar = reinterpret_cast&

  • LinuxPenseur
    c++ casting static-cast
    Consider the following sample code.#include <iostream>using namespace std;class base {public:void func(){cout << “base::func()” << endl;}};class derived : public base {public:void func(){cout << “derived::func()” << endl;}};void dummy(base *bptr) {derived *dptr = static_cast<derived*> (bptr);dptr->func(); }int main() {base bob1;derived dob1;dummy(&dob1); //Line1dummy(&bob1); //Line2 }In Line1, I am passing the address of a derived class object to fu

Web site is in building