Search code examples
c++castingoperator-overloading

c++ casting char* to object?



Is it possible in C++ to convert an array of chars to an object like so:

char* bytes = some bytes...
MyObject obj = (MyObject)(bytes);

?
How do I have to define the cast operator?
thanks :)


Solution

  • You probably want to define a constructor for MyObject:

    class MyObject {
    public:
      explicit MyObject(const char* bytes);
      ...
    };
    
    MyObject::MyObject(const char* bytes) {
      // do whatever you want to initialize "MyObject" from the byte string
    }
    

    and then you can use it:

    char* bytes = some bytes...
    MyObject obj = MyObject(bytes);  // this will work
    MyObject obj(bytes);             // so will this