Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shadowed parameter

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

like image 247
calccrypto Avatar asked Jun 10 '11 15:06

calccrypto


People also ask

What is shadowing a parameter?

Declaring a variable with a name that already refers to another variable is called shadowing.

What is shadowing in coding?

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.

What does shadowing mean in C++?

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.

What is no shadowed variable?

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.


2 Answers

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.

like image 123
larsmoa Avatar answered Oct 25 '22 01:10

larsmoa


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.

like image 37
Didier Trosset Avatar answered Oct 25 '22 01:10

Didier Trosset