3

So I have the following code which works nicely:

CMyClass& CMyClass::operator=(DWORD rhs) 

...

CMyClass exc;
exc = GetLastError();

And it does everything I expect it to (call the stuff inside the = operator.) I was wondering how to get it so that I can instead write it like the following:

CMyClass exc = GetLastError();

I tried using the above and it doesn't call the = operator functionality, instead just leaving me with a class where just the default constructor has been called.

Thanks

Luke
  • 560
  • 6
  • 26

1 Answers1

4

A constructor is required.

CMyClass(DWORD rhs)

Or explicit

explicit CMyClass(DWORD rhs)

Be warned, the implicit constructor allows this to compile;

CMyClass exc = GetLastError();

But it also participates in compiler generated implicit constructions and conversions. It is generally better to have to be explicit and write;

CMyClass exc ( GetLastError() );
Niall
  • 30,036
  • 10
  • 99
  • 142
  • OK, thanks. Could you please clarify what you mean by `it also participates in compiler generated implicit constructions and conversions` – Luke Sep 01 '14 at 08:45
  • 2
    Basically, if another type say, `class ABC` has an type conversion to `DWORD` (`operator DWORD();`), then this would also compile; `CMyClass exc = abc;` where `abc` is an instance of `ABC`. Or worse, if `CMyClass` was an argument to a function `void Func(CMyClass)`, then this would compile `Func(abc)` – Niall Sep 01 '14 at 08:47
  • @Luke, See [here](http://stackoverflow.com/q/121162/3747990) for some more detail on explicit. The first answer basically has the same example as I gave you. The second answer has some more reasons... Best advice is to generally (by default) add the explicit, unless it is required to not be there. – Niall Sep 01 '14 at 09:05