why is the second constructor shadowing the first?
class RC2{
private;
bool keyset;
public:
RC2(uint32_t t1 = 64){
keyset = false;
}
RC2(const std::string KEY, uint32_t t1 = 64){
RC2(t1);
//setkey(KEY);
}
};
is giving me:
error: declaration of 'RC2 t1' shadows a parameter
i would think that there is no way for the compiler to mess up distinguishing between these
im using codeblocks gcc with C++0x
Declaring a variable with a name that already refers to another variable is called shadowing.
In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables), this is known as name masking.
So what happens when we have a variable inside a nested block that has the same name as a variable in an outer block? When this happens, the nested variable “hides” the outer variable in areas where they are both in scope. This is called name hiding or shadowing.
Rationale. When a variable in a local scope and a variable in the containing scope have the same name, shadowing occurs. Shadowing makes it impossible to access the variable in the containing scope and obscures to what value an identifier actually refers.
Because RC2(t1);
is a local variable declaration shadowing argument t1
, not a call to the other constructor. The following code is also valid:
int main(int argc,char* args[])
{
int(a);
a = 2;
return a;
}
Note! Before C++11, there was no way to call another constructor on the same class from an constructor in C++. If you are using an old C++ version make an Init()
-method which both constructors invoke.
The error is not triggered by the constructor declaration.
The error is raised on the line that declares a variable t1
of type RC2
in the block of the second constructor. This variable shadows the similarly named t1
variable passed a an argument to the constructor.
I guess your intention with RC2(t1);
was to call the other constructor, but this is not possible in C++. It will be possible in C++2011, but using another syntax.
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