Heres the link to code and the error
I dont understand why the line return (const C&)cc; doesnt work.
Heres a paste of code and error
#include <stdio.h>
class C
{
public:
int i;
explicit C(const C&) // an explicit copy constructor
{
printf("\nin the copy constructor");
}
explicit C(int i ) // an explicit constructor
{
printf("\nin the constructor");
}
C()
{
i = 0;
}
};
class C2
{
public:
int i;
explicit C2(int i ) // an explicit constructor
{
}
};
C f(C c)
{ // C2558
// c.i = 2;
// return c; // first call to copy constructor
C cc;
return (const C&)cc;
}
void f2(C2)
{
}
void g(int i)
{
// f2(i); // C2558
// try the following line instead
f2(C2(i));
}
int main()
{
C c, d;
d = f(c); // c is copied
}
Output:
In function ‘C f(C)’: Line 36: error:
no matching function for call to
‘C::C(const C&)’ compilation
terminated due to -Wfatal-errors.
Examples of calling the explicit copy-constructor:
Of course, pass-by-value and return-by-value always call the copy constructor implicitly, so declaring the copy constructor explicit will prevent this (not necessarily a bad thing).