J
Jean Stax
Hi !
I tried to understand when the explicit attribute in copy constructor
prevents from
me to create a new object. Bellow is the sample code.
While the two first cases really generate a compilation error, the
third (mc2 = Foo1()
compiles and runs without any problem. I am
wondering why the:
MyClass Foo1()
{
MyClass mc(1);
return mc;
}
isn't forbidden, when MyClass copy constructor is defined as explicit.
Thanks.
class MyClass
{
public:
MyClass(int nVal) : m_nVal1(nVal){}
MyClass() : m_nVal1(0){}
explicit MyClass(const MyClass& copy)
{
//...
}
private:
int m_nVal1;
};
void Foo(MyClass cc)
{
}
MyClass Foo1()
{
MyClass mc(1);
return mc;
}
int main(int argc, char* argv[])
{
MyClass mc(1);
MyClass mc1 = mc;
//error C2440: 'initializing' : cannot convert from 'class MyClass' to
//class MyClass' No copy constructor available for class 'MyClass'
Foo(mc);
//error C2664: 'Foo' : cannot convert parameter 1 from 'class MyClass'
//to 'class MyClass'No copy constructor available for class 'MyClass'
MyClass mc2;
mc2 = Foo1();
return 0;
}
I tried to understand when the explicit attribute in copy constructor
prevents from
me to create a new object. Bellow is the sample code.
While the two first cases really generate a compilation error, the
third (mc2 = Foo1()
wondering why the:
MyClass Foo1()
{
MyClass mc(1);
return mc;
}
isn't forbidden, when MyClass copy constructor is defined as explicit.
Thanks.
class MyClass
{
public:
MyClass(int nVal) : m_nVal1(nVal){}
MyClass() : m_nVal1(0){}
explicit MyClass(const MyClass& copy)
{
//...
}
private:
int m_nVal1;
};
void Foo(MyClass cc)
{
}
MyClass Foo1()
{
MyClass mc(1);
return mc;
}
int main(int argc, char* argv[])
{
MyClass mc(1);
MyClass mc1 = mc;
//error C2440: 'initializing' : cannot convert from 'class MyClass' to
//class MyClass' No copy constructor available for class 'MyClass'
Foo(mc);
//error C2664: 'Foo' : cannot convert parameter 1 from 'class MyClass'
//to 'class MyClass'No copy constructor available for class 'MyClass'
MyClass mc2;
mc2 = Foo1();
return 0;
}