Hi,
What is the advantage of conversion function over assignment operator overloading.
and why there is no return type in the conversion function though it returns an object
Printable View
Hi,
What is the advantage of conversion function over assignment operator overloading.
and why there is no return type in the conversion function though it returns an object
Conversion functions (usually called cast functions) are for a completely different purpose than the assignment operator. The assignment operator assigns an object to another object of the same type. The cast function converts it to another type. And cast functions certainly do have return types, and they do not have to return objects.
Code:struct foo {
foo & operator = (const foo & other){ bar = other.bar; } //assignment
operator float(void){ return (float)bar; } //cast
private:
int bar;
};
foo a;
foo b;
a = b; //assignment
float f = (float)a; //cast
Well lets try to not confuse the OP.
A cast operator does not declare the return type in its signature, because it is already included in the name. It is just a syntax quirk:
This will cast to char*. It WILL return an "object", which will be of the type of the cast (here, it will return a char*). Note that the term "object" is used in a broad sense here, and can be a class, a pointer, a reference, etc...Code:operator char*()
----
It is actually usually considered bad design to provide cast operators, as it can lead to unexpected call. Explicit conversion is usually regarded as a superior alternative.
Correct me if I'm wrong, can't you declare the cast operator with "explicit" like you do with constructors to avoid those unexpected calls?
That's not correct. An assignment operator can take a different type of RHS than the type of the LHS, i.e. the assignment operator can be overloaded. When both types are the same, we are actually talking about the copy assignment operator. However, since other overloads of the assignment operator are used so rarely, most people just talk about the assignment operator when they mean the copy assignment operator.
I see, I assumed you could use it with different parameters that just a const reference to it's own type, I've just never seen it. This seems dangerous for the same reason cast operators are, possible unexpected calls to it.