lundi 6 février 2023

conversion from void pointer to pointer to struct or class

what is the correct approach for converting void * to pointer to struct or class.

sometime mistakes can happen like pointer to different class or struct was assigned.how to catch these types of mistakes over compile or run time.

following program tried, surprisingly it compiled and no crash even after execution.

what is right way for type casting from void * to pointer to struct or class in cpp

Description: how to avoid type casting related issues from void * to pointer to class or struct at compile time or runtime. if static_cast is used for conversion from void * then code is compiled, even it is invalid conversion.

#include <iostream> using namespace std;

struct stu { int x; int y; int z; };

struct clg { int x; float y; char z; };

void fun(void *msg) { clg myclg = static_cast<clg>(msg);

cout<<"casting is done."<<endl;

}

int main() { stu* st = new stu(); clg* cl = new clg();

void *ptr = st;
fun(ptr);

return 0;

}

Aucun commentaire:

Enregistrer un commentaire