c++ - Operator overloading without explicit type casting -


i try make own small string class practice purposes. want overload const wchar_t* operator return buffer saved within string object fails, when access object. it's conversion operator isn't called. works, when explicitly type cast object via (const wchar_t*) mystring

edit:

// cstring.h class cstring { private:     wchar_t* _string;      void set(const wchar_t text[]);  public:     cstring();     cstring(const wchar_t text[]);     cstring(const cstring& text);      ~cstring();      operator const wchar_t*() const; };  // cstring.cpp #include "cstring.h"  cstring::cstring() { set(l""); } cstring::cstring(const wchar_t text[]) { set(text); } cstring::~cstring() { delete[] _string; }  void cstring::set(const wchar_t text[]) {     delete[] _string;      _string = new wchar_t[wcslen(text)];     wcscpy(_string, text); }  cstring::operator const wchar_t*() const {     return _string; }  // main.cpp int main() {     cstring* helloworld = new cstring(l"test 123");      messagebox(null, helloworld, l"", mb_ok);       // doesn't work     messagebox(null, (const wchar_t*) helloworld, l"", mb_ok);  // works, don't explicitly want use cast everytime.      return 0; } 

first, if working in windows, cstring class atl/mfc. reusing same name class of own rude.

if aren't, should provide signature messagebox.

i'll assume working in windows world.

your problem cstring* not same thing cstring. defined operator turn cstring wchar_t const*. not surprisingly, doesn't work cstring*.

change definition of helloworld cstring helloworld = cstring(l"test 123"); -- no new, no pointers -- , code works.

as yet aside, explicit cast did results in undefined behavior, reinterprets pointer object pointer buffer of characters. 1 of many, many reasons why using c-style casts bad idea, because difference between reinterpret cast , static cast requires lot of context. see error, change messagebox call messagebox( null, static_cast<const wchar_t*>(helloworld), l"", mb_ok); did code explicit cast ever run , print sensible?

if must put helloworld in free store, dereference when using (in both implicit, , explicit cast cases). ie, replace uses of helloworld *helloworld. advise against -- there no reason store particular instance on free store.


Comments