Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the 'hides constructor for' warning mean when compiling C++ with g++?

Tags:

c++

g++

Using the following code:

#include <stdio.h>


struct my_struct {
        int a;
        int b;
        my_struct();
};

my_struct::my_struct(void)
{
        printf("constructor\n");
}

void my_struct(void)
{
        printf("standard function\n");
}

int main (int argc, char *argv[])
{
        struct my_struct s;
        s.a = 1;
        s.b = 2;

        printf("%d-%d\n", s.a, s.b);

        return 0;
}

I get a warning compiling with g++ -Wshadow main.cpp:

main.cpp:15:20: warning: ‘void my_struct()’ hides constructor for ‘struct my_struct’

I would be ok with that warning if the void my_struct function actually replaced the my_struct::my_struct one. But it does not appears to be the case. If I run the program, I get:

constructor
1-2

Any idea what this warning mean ? It is quite annoying especially when I include C headers into C++ code

like image 619
mbonnin Avatar asked Sep 30 '11 10:09

mbonnin


2 Answers

The warning points out that the my_struct() function has the same name as the my_struct structure. It means you will be unable to write:

my_struct s;         // Error.

Because the compiler will think that you're using a function as a type. However, as you probably realized, you can still instantiate your structure with the struct keyword:

struct my_struct s;  // Valid.
like image 92
Frédéric Hamidi Avatar answered Oct 21 '22 04:10

Frédéric Hamidi


void my_struct(void) has the same name of your class/struct and since it is in the global namespace it is conflicting with your class/struct's constructor.

You could try something like:

#include <cstdio>


struct my_struct {
        int a;
        int b;
        my_struct();
};

my_struct::my_struct(void)
{
        printf("constructor\n");
}
namespace mbonnin
{
 void my_struct(void);
}

void mbonnin::my_struct(void)
 {
         printf("standard function\n");
 }

int main (int argc, char *argv[])
{
        my_struct s;
        s.a = 1;
        s.b = 2;

        printf("%d-%d\n", s.a, s.b);
        mbonnin::my_struct();

return 0;
} 

And by the way the struct in struct my_struct s; is redundant in C++.

like image 37
Sadique Avatar answered Oct 21 '22 06:10

Sadique