conversion operators (operator keyword)

  • Thread starter Egbert Nierop \(MVP for IIS\)
  • Start date
E

Egbert Nierop \(MVP for IIS\)

Example...



This would make that i can assign a ULONG to a CComBSTR2 class while the
body of the code performs necessary conversion.

CComBSTR2& operator=(ULONG ulong)

{

}

QUESTION: Can I do it the other way around as seen below?



// code below does compile but still has no effect.

ULONG& operator=(const &CComBSTR2)

{

}
 
C

Carl Daniel [VC++ MVP]

Egbert said:
Example...

This would make that i can assign a ULONG to a CComBSTR2 class while
the body of the code performs necessary conversion.

I'm going to assume that you meant both of these examples to be members of
CComBSTR2...

CComBSTR2& operator=(ULONG ulong)
{
}

QUESTION: Can I do it the other way around as seen below?

// code below does compile but still has no effect.
ULONG& operator=(const &CComBSTR2)
{
}

The problem is that if you write

CComBSTR2 bs2;
ULONG ul;

ul = bs2;

The compiler will never look for an overload of operator= in the CComBSTR2
class. It will only search the "associated namespaces" and the ULONG class
itself. Of course, ULONG is a built-in, so all of that is moot, as it's
impossible to overload any operators for a built-in type (i.e. make
operators that behave as if they're member functions of the built-in type).

What you want instead is a conversion operator

operator ULONG()
{
// convert your string to ULONG
}

Then your assignment to ULONG will succeed.

Generally this kind of conversion function is discouraged - having an
implicit conversion to an integer type will cause many code constructs that
were actually errors to be legal code.

Instead, it's generally preferred that you write an explicit conversion:

ULONG ToULong()
{
// convert your string to ULONG
}

and call it explicitly when you need to assign to a ULONG.

-cd
 
E

Egbert Nierop \(MVP for IIS\)

Carl Daniel said:
I'm going to assume that you meant both of these examples to be members of
CComBSTR2...


Your suggestion was OK. thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top