Monday, August 20, 2007

Problem with Implicit conversion

Hi,
there is a serious issue in implicit conversion . what is that ? Some times we get some unintended situation in implicit conversion. Lets have an example which tels this problem.

#include
using namespace std;
class String
{
char * ptr;
public:
/* explicit */ String (int n) //allocate n bytes to the String object
{
ptr = new char[n];
cout<<"int cotr \n"; } String( char *p) // initializes object with char *p { cout<<"char * cotr \n"; ptr= p; } void show() { cout<< s="'a';" s="'a';">.

But this is not what the we have intended. So to prevent such conditions, we can define the class's constructor as explicit.
Just remove comment line /* explicit */
class String
{
//....public:
//....
explicit String (int n); //allocate n bytes
String(const char *p); // initialize sobject with string p
}
Some more example i found from net , Yee Ley .. :)

#include
#include
class T
{
public:
explicit T(int i): data_(i) { std::cerr << "T::T(int)" << std::endl; }
template
operator X() const
{
X x; std::cerr << "T::operator X()" << std::endl; return x;
}
private:
T(const T&) { std::cerr << "T::T(const T&)" << std::endl; }
int data_;
};

int main(int, char**)
{
T t(3); // OK
std::string s1 = t; // OK.
std::string s2(t); // Error: ambiguity.
}

The reason is that std::string has two constructors with a single parameter, taking resp. a const char* or std::string argument.
std::string::string(const char*);
std::string::string(const std::string&*);

Due to the member template, the compiler can convert to both const char* and std::string, with similar "matching quality". Hence the ambiguity.



#include
#include
class T
{
public:
explicit T(int i): data_(i)
{
std::cerr << "T::T(int)" << std::endl;
}
template
operator X() const
{
X x;
std::cerr << "T::operator X()" << std::endl; return x;
}
private:
T(const T&)
{
std::cerr << "T::T(const T&)" << std::endl;
}
int data_;
};
int main(int, char**)
{
T t(3);
std::string s = t;
}

which compiles ok and produces the output T::T(int)
T::operator X()

showing once more that the compiler optimized away the theoretical call to T's copy constructor, in this case by directly putting the result of T::operator std::string(t) in s.






I think ,it is clearlly understood , you can allways reach me
hara.sahu@gmail.com
sahu

No comments: