Case 1:
If there is a type T and another type F . An the type T has a constructor that takes in a Type F , in that case in expressions which involve the usage of Type T and an object of type F is passed . The type F is automatically converted to an object of type T . Lets see this is as example
Now here if print is invoked with "Hello , world" i.e print("Hello , world") is called then since we have a constructor for String that takes in an array of characters . So array of characters are automatically converted into a String object which is then passed to then print function .
class String {
char * string;
public:
String(const char * str = "");
};
void print(String & str);
Case 2:
Using the conversion operator it is possible to implicitly convert one object to another type. If the String class had the following operator defined
operator const char* ( ) const { return string; }
and somewhere in some function if the following code was used
String s("hello world");
cout << style="font-weight: bold;">So, with that also an implicit type conversion happens . Implicit type conversion can get confusing , so should be used with care . Explicit case or function calls are much better as they indicate the intended operation more clearly .
No comments:
Post a Comment