Saturday 15 August 2015

c++ - Is it safe to cast from a pointer to a child variable to a pointer to a parent variable? -



c++ - Is it safe to cast from a pointer to a child variable to a pointer to a parent variable? -

the next code works (on ideone, borland bcb 6 , gcc)

#include <stdio.h> class base of operations { private: base of operations **bptr; public: base(void *ptr) { bptr = (base **)ptr; *bptr = this; } virtual ~base() { if(bptr) *bptr = null; printf("base aufgelöst\n"); } }; class kid : public base of operations { public: child(void *var) : base(var) {} ~child() { printf("child aufgelöst\n"); } }; int main() { kid *ptr = null; new child(&ptr); printf("childptr: %p\n", ptr); delete ptr; printf("childptr: %p\n", ptr); homecoming 0; }

the output of above programme is:

childptr: 0x9cc0008 kid aufgelöst base of operations aufgelöst childptr: (nil)

which expected , want.

my question simple: safe or seem work? because sense little bit hacky first implicitly cast pointer of type child void * , cast base ** or there obvious (or hidden) problems this?

thank much.

edit: since there seemed bit of misunderstanding regarding intention:

the sole purpose of 'hack' null variable in question, 1 time object gets destroyed protect myself against accidentally forgetting null variable manually , perchance accessing invalid memory later on.

the variable must , not used access other functionality of classes.

however, tried (and worked) before following:

void freefunc(void *ptr) { if(ptr) { base of operations **bptr = (base **)ptr; delete *ptr; //calls destructors *ptr = null; } }

which appears worse replies had been getting on here far?

casting kid * base of operations * safe. casting child** base** not because unrelated. problem doing if cast void * base**, can assign base of operations * pointer of type derived *, this:

#include <iostream> class base of operations { public: virtual void foo() { std::cout << "base::foo" << std::endl; } }; class kid : public base of operations { public: virtual void foo() { std::cout << "child::foo" << std::endl; } virtual void bar() { std::cout << "child::bar" << std::endl; } }; void main() { kid *d = new child(); base of operations *b = d; kid **d2 = &d; base of operations **b2 = (base **)(void *)d2; // forcefulness *b2 = new base(); // whoops! kid *d points instance of base of operations * d->bar(); }

c++ pointers

No comments:

Post a Comment