Luke
Luke

Reputation: 560

Class constructor using other object

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

Upvotes: 3

Views: 50

Answers (1)

Niall
Niall

Reputation: 30605

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() );

Upvotes: 4

Related Questions