Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 980
Luke Avatar asked May 14 '26 18:05

Luke


1 Answers

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() );
like image 196
Niall Avatar answered May 17 '26 07:05

Niall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!