Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function and struct having the same name in c++

Tags:

c++

The following code compiles in C++

struct foo
{
    int a, b;
};

struct foo foo()
{
    struct foo a;
    return a;
}

int main(void) {
    foo();
    return 0;
}
  1. Is it supposed to be allowed to have a struct and a function with the same name ?
  2. Since it compiles I then go on and try to declare an object of type foo. Is there a way? It seems impossible to do :

    foo a;   // error: expected ‘;’ before ‘a’
    foo a{}; // error: expected ‘;’ before ‘a’
    foo a(); // most vexing parse would kick in any way
    
like image 787
Nikos Athanasiou Avatar asked Apr 27 '14 21:04

Nikos Athanasiou


1 Answers

Yes, this is allowed we can see this by going to draft C++ standard section 3.3.10 Name hiding paragraph 2 and it says (emphasis mine):

A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member, function, or enumerator declared in the same scope. If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.

In this case using struct in the declaration would fix your issue:

struct foo a;
like image 185
Shafik Yaghmour Avatar answered Oct 28 '22 02:10

Shafik Yaghmour