I have one simple question. What is the reason of compilation failure?
template <class T>
class test
{
T varGoodForNothing;
public:
test()
{ }
test(test<T> & tt)
{
varGoodForNothing = tt.varGoodForNothing;
}
test<T> & operator=(const test<T> & tt)
{
if (this == &tt)
return *this;
test(tt);
return *this;
}
};
Compiler error is:
declaration of test tt shadows a parameter.
The standard says that a declaration of type Type (name) is the same has having used Type name, see the below standard quotation.
[dcl.meaning] / 6
In a declaration
T DwhereDhas the form( D1 )The type of the contained declarator-id is the same as that of the contained declarator-id in the declaration
T D1.Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.
With that said you are not calling the copy-constructor of test with an argument named tt, instead the compiler thinks that you are trying to declare a variable of type test with the name tt.
To circumvent the problem of T (D); being interpreted as T d; we will have to wrap T inside parentheses, such as in the below.
(test) (tt);
Note: Even if the code will compile after the proposed change it will not do what you want, nor think, it will.
Instead of calling the copy-constructor of test for the given instance you will declare an anonymous instance of test initialized with the value of tt.
Constructors can only be called from within other constructors (using a member initializer list).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With