S
subramanian100in
Consider the following program:
#include <iostream>
#include <string>
using namespace std;
class Test
{
public:
Test();
Test(const Test &rhs);
Test(const std::string &str);
private:
int x;
};
Test::Test()
{
x = 0;
cout << "default ctor called x = " << x << endl;
}
Test::Test(const Test &rhs)
{
x = rhs.x;
cout << "copy ctor called. x = " << x << endl;
}
Test::Test(const std::string &str)
{
cout << "Test(const std::string &str) - str = " << str << endl;
}
int main()
{
Test str_obj = "test";
return 0;
}
This program produces the following compilation error for the
statement
Test str_obj = "test";
in g++ under Linux.
error: conversion from `const char[5]' to non-scalar type `Test'
requested
But it compiles well in VC++ 2005 express edition produces the
following output:
Test(const std::string &str) - str = test string
Why is this difference ? I do not understand as to why it doesn't
compile under one implementation(ie g++) but produces output under
another(ie VC++). What does the Standard say in this case ?
But if I used
Test str_obj("direct initialization");
this statement is compiled without any error in g++ under Linux and
produces the expected output.
Kindly explain.
Thanks
V.Subramanian
#include <iostream>
#include <string>
using namespace std;
class Test
{
public:
Test();
Test(const Test &rhs);
Test(const std::string &str);
private:
int x;
};
Test::Test()
{
x = 0;
cout << "default ctor called x = " << x << endl;
}
Test::Test(const Test &rhs)
{
x = rhs.x;
cout << "copy ctor called. x = " << x << endl;
}
Test::Test(const std::string &str)
{
cout << "Test(const std::string &str) - str = " << str << endl;
}
int main()
{
Test str_obj = "test";
return 0;
}
This program produces the following compilation error for the
statement
Test str_obj = "test";
in g++ under Linux.
error: conversion from `const char[5]' to non-scalar type `Test'
requested
But it compiles well in VC++ 2005 express edition produces the
following output:
Test(const std::string &str) - str = test string
Why is this difference ? I do not understand as to why it doesn't
compile under one implementation(ie g++) but produces output under
another(ie VC++). What does the Standard say in this case ?
But if I used
Test str_obj("direct initialization");
this statement is compiled without any error in g++ under Linux and
produces the expected output.
Kindly explain.
Thanks
V.Subramanian