Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redefinition of a variable with a different type [duplicate]

Tags:

c++

sorry for the question title but I didn't know a correct title for my problem. I have the following code example:

struct test {
    test(int a) {
    }
};

int main() {
    test(1);
    return 0;
 }

The above example code works. Now i do (in my understanding) the same a bit differently:

struct test {
     test(int a) {
     }
};

int main() {
    int a = 0;
    test(a);
    return 0;
}

When I compile this I get the following error:

error: redefinition of 'a' with a different type: 'test' vs 'int'

But in my opinion it gets really strange when I try this:

struct test {
    test(int a) {
    }
};

int main() {
    int a = 0;
    test((int)a);
    return 0;
}

the above example works again and really confuses me since I don't see the difference (except casting an int to an int). Can anyone explain what's going on? Thank you in advance.

like image 254
roohan Avatar asked Nov 11 '19 09:11

roohan


1 Answers

You forgot to give your test variable a name, causing test(a); to be a declaration of a variable named a of type test.

In the other cases, since test(1) and test((int)a) cannot be declarations, but must be some kind of call, your compiler will treat that as constructing a temporary object of type test without a name.

like image 136
Max Vollmer Avatar answered Oct 05 '22 23:10

Max Vollmer