user81993 user81993 - 26 days ago 20
C++ Question

If there is a class and a variable by the same name in the same scope, how to specify the class?

picture time!

struct my_struct {
___________ class name (A)

struct pineapple {};
pineapple pineapple;
↑______________ variable name (B)

____________ seems to be referring to B instead of A

my_struct(pineapple pineapple) {
this->pineapple = pineapple;
}
};


So there is a class and a variable sharing the same name. While this normally doesn't bother c++, in case of function parameters(such as the constructor there), it seems to prefer the name of the local variable over the class.

Is there a way to specify that I mean the class and not the variable?

Answer

Why would you do that to yourself?

Anyhow, you can use the elaborated type specifier to disambiguate:

struct my_struct {
    struct pineapple {};
    pineapple pineapple;

    my_struct(struct pineapple pineapple) {
              ^^^^^^
        this->pineapple = pineapple;
    }
};

demo

That being said, this is really weird design, I'd avoid it.

Comments