If I write this program:
#include <iostream>
namespace foo {
    struct bar {
        int x;
    };
}
int main (void) {
    struct foo::bar *a = new struct foo::bar;
    delete a;
    return 0;
}
and compile it with:
g++ main.cxx -Wall -Wextra
It gives me this warning:
main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]
However, if I take out the struct keyword after the new keyword:
#include <iostream>
namespace foo {
    struct bar {
        int x;
    };
}
int main (void) {
    struct foo::bar *a = new foo::bar;
    delete a;
    return 0;
}
and compile it the same way, g++ outputs no warnings.  Why does g++ output that warning if I use the struct keyword?
In C++, the struct keyword defines a type, and the new type no longer needs the struct keyword.  This is one of the many differences between C and C++.
Examining the error:
main.cxx:10:39: warning: declaration
‘struct foo::bar’does not declare anything [enabled by default]
g++ thinks you're declaring a new struct with the name foo::bar instead of allocating memory of type struct foo::bar. My guess would be because g++ assumes any usage of struct that doesn't declare an lvalue is for the purpose of declaring a type.
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