0

Saw the header definition from a library

operator const wchar_t*() const

anyone can explain to me why the above defined a cast operator?

Denis Ermolin
  • 5,530
  • 6
  • 27
  • 44
Adam Lee
  • 24,710
  • 51
  • 156
  • 236
  • 4
    Because that's what the language definition says? Please clarify what you're asking. – Pete Becker Nov 29 '12 at 14:37
  • You define an operator whose name is a type name, so it's not too surprising that it is a cast operator, IMO. – Daniel Fischer Nov 29 '12 at 14:38
  • This sounds like "why did chicken cross the road?" question. Could you please clarify what are you trying to ask? "Why is this syntax interpreted as conversion operator?" "Why did they need a conversion operator?" Some other kind of "why?" – AnT stands with Russia Nov 29 '12 at 14:55

3 Answers3

1

For example, you want cast a object into wchar_t *, this operator would be supplied.

e.g.

MyString a("hello"); // is a string hold ansi strings. but you want change into wide chars.
wchar* w = (wchar_t*)a; // will invoke the operator~
Sasha
  • 492
  • 2
  • 6
  • 21
Healer
  • 290
  • 1
  • 7
1

Its the syntax of the language. C++ allows you to create your own Operators

For example:

struct A {
    bool operator==(const int i);
    bool operator==(const char c);
    bool operator==(const FOO& f);
}

This allows use to conveniently compare our type which a syntax that looks nicer. A a; if(a == 5) {} the alternative is implementing an equals(int value) methods all over that looks something like A a; if(a.equals(5)) {}.

The same is true for casting.

struct Angle {
    float angle;
    operator const float() const {return angle;}
}

Angle theta;
float radius = 1.0f;
float x = radius*cos(theta);
float y = radius*sin(theta);

In conclusion its just a nice feature of the language that makes our code look much nicer and more readable.

andre
  • 7,018
  • 4
  • 43
  • 75
1

Any member function of the form operator typename() is a conversion function.

const wchar_t* is a type name, therefore operator const wchar_t*() is a conversion function.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644