0

I came across this operator overload during my use of the sqlapi which does exactly what i need, but i'm not sure how it works.

sqlapi.h

class SQLAPI_API SAString
{
public:
//stuff

//! Return pointer to const string
operator const SAChar *() const;

//stuff
}

The only way that i know how to use it is because of the intellisense which doesn't look pretty:

char* chPointer = SAStringObj.operator const SAChar*();

Questions:

Is there a better looking way to call this overloaded operator?

Can someone dissect what this function header tells us about the function?

"*operator const SAChar () const;"

shawn a
  • 799
  • 3
  • 13
  • 21

1 Answers1

3

This is an implicit cast operator for converting an SAString to const SAChar *. It is implicitly invoked whenever you use an SAString in a context in which a const SAChar * is expected (unless it would be ambiguous).

void foo(const SAChar *);

SAString myString("bar");

foo(myString);
const SAChar *myCharPtr = myString;

You can use a static_cast to force it in other contexts:

static_cast<const SAChar *>(myString)

You can use boost::implicit_cast which is safer:

boost::implicit_cast<const SAChar *>(myString)

In C++11 you can have an explicit cast operator which is only valid in explicit cast contexts:

explicit operator const SAChar *() const;

The const at the end has the usual meaning, just as for ordinary member functions.

Community
  • 1
  • 1
Oktalist
  • 14,336
  • 3
  • 43
  • 63
  • Wow, that answer was perfect and answered all my questions. Also, is there any difference between a standard "(const SAChar*)myString" cast and a static_cast? – shawn a May 10 '15 at 01:25