-1

I had to change the prototype of a function getData() which is basically a legacy source code. Upon changing it from returning a char* as shown below, I started getting compile errors due to static_cast.The question I have is , Is it safe to use reinterpret_cast, instead of static_cast?

  class C1{

     public:

     //void *getData() {return data;} //Legacy implementation*
     char *getData() {return data;}  //My new implementation

     private:
       char data[100];
   };

   int main()
   {
       C1 myobj;   
       unsigned char* begin;

       begin=static_cast<unsigned char*>(myobj.getData());  *//<== This gives compile error.use reinterpret_cast ?*
       return 0;
   }

Is there a better solution than reinterpret_cast ?

deep_rugs
  • 307
  • 3
  • 5
  • 2
    why isn't `begin` a `char*`? – default May 07 '18 at 14:55
  • what's the error message? – default May 07 '18 at 14:55
  • Well that's the way they have it right now .... They also cast it to char * or even other different types like a struct etc. – deep_rugs May 07 '18 at 14:58
  • `main.cpp: In function 'int main()': main.cpp:31:54: error: invalid static_cast from type 'char*' to type 'unsigned char*' begin=static_cast(myobj.getData()); //<== Legacy : This gives compile error.` – deep_rugs May 07 '18 at 15:00
  • 3
    Possible duplicate of https://stackoverflow.com/questions/10151834/why-cant-i-static-cast-between-char-and-unsigned-char – izlin May 07 '18 at 15:00
  • 1
    @deep_rugs If `getData()` is supposed to return some untyped buffer where the caller determines how it's interpreted, I think you were wrong to change `getData()` to return `char *` and should just change it back to return `void *`. –  May 07 '18 at 15:15

2 Answers2

3

You can static_cast from a void * to any pointer type, or between pointers to related types in the sense when one herites from the other.

reinterpret_cast is intended to be used between pointers to unrelated types. Is is equivalent to a static_cast from first type to void * followed with a static_cast from void * to second type. It T and U are unrelated types:

U *u = ...;
T *t;

t = reinterpret_cast<T *>(u);  /* strictly the same as would be
t = static_cast<T *>(static_cast<void *>(u));  */
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • If you have `int i{}` then `reintrepret_cast(&i)`. Does the C++ standard guarantee that the resulting address will be the same as `reintrepret_cast(&i)` ?? –  Mar 01 '22 at 07:10
0

It depends of what you want to accomplish. If you want to just use the bitwise representation of data, with each element interpreted as unsigned char, then reinterpret_cast is the way to go.

Your question doesn't give us enough details to figure out if it is "safe" in your case.

gflegar
  • 1,583
  • 6
  • 22