operators for type conversion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class String {
public:
  String(const char *value);        // see Item 11 for pos-
  ~String();                        // sible implementations;
                                    // see Item M5 for comments
                                    // on the first constructor
  operator char *() const;          // convert String -> char*;
                                    // see also Item M5
  ...

private:
  char *data;
};
const String B("Hello World");      // B is a const object


char *str = B;               // calls B.operator char*()


Isn't argument needed for the operator function, so it can decide what to convert?

Thanks.
Last edited on
It converts the object from which is called, in your case 'B'
Thats a good amount of syntactic variation for an operator.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//For an operator[]
char& operator[] (int index)
{
  return data[index];
}

//function call:
B[0];

//For an operator *
char& operator*(int x, int y);
{
  return (x*y);
}

//function call:
B[0]*B[1];

In both these above examples, the calling object is on the left and it becomes easy to remember the syntax.

The one in question:
1
2
3
4
5
6

operator char *() const;

//function call:
char *str = B;


Object is on the right and syntax is not very intuitive.

It seems like the only way to remember is to cram the operators in one's head or is there another way?
Last edited on
Well other operators are declared this way:
ReturnType operator Symbol ( arguments );
Conversion operator is declared this way:
operator DataType ( void );
Because the DataType is the return type and you don't need arguments

If you want a more intuitive syntax try this:

char* operator = ( char* destination, const String &str );

(You may have to declare it as friend in String)
 
char* operator = ( char* destination, const String &str );


Above example you gave is a "=" operator and function call would be

A = B

And the equivalent function call is

A. operator=(B)

That's no problem.

But operator DataType ( void ); should help.
And the equivalent function call is
A. operator=(B)

Not really, it just calls the operator. An operator don't have to be a member function
That helps. Thanks.
Topic archived. No new replies allowed.