#include <iostream>
using namespace std;
struct test
{
test(){cout<<"class"<<endl;}
};
void test(){cout<<"function"<<endl;}
int main()
{
test();
return 0;
}
Output:
function
(VS2013 ang gcc 4.8.1)
Why function is selected? Isn't it ambiguity?
In C++, function overloading is possible i.e., two or more functions from the same class can have the same name but different parameters. However, if a derived class redefines the base class member method then all the base class methods with the same name become hidden in the derived class.
When you give the class the name ABC , that name is no longer associated with the function. Just the same as reassigning a variable.
Constructor. A constructor is function of a class that is called whenever an object is created. It is usually used to assign values to the variables of the class. There is also a same function which has the same name as that of its class is Destructor, It juts have tilde (~) sign at the beginning.
Yes, it's called function overloading. Multiple functions are able to have the same name if you like, however MUST have different parameters.
This is called name hiding and described in
4) Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,
— they shall all refer to the same entity, or all refer to functions and function templates; or
— exactly one declaration shall declare a class name or enumeration name that is not a typedef name and the other declarations shall all refer to the same variable or enumerator, or all refer to functions and function templates; in this case the class name or enumeration name is hidden (3.3.10). [...]
emphasis mine.
Note that changing the order of declaration doesn't affect the outcome:
void test(){cout<<"function"<<endl;}
struct test
{
test(){cout<<"class"<<endl;}
};
int main()
{
test();
return 0;
}
still prints out function
.
In case it isn't obvious, don't do this :)
From N3485 §3.3.10 [basic.scope.hiding]/2:
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.
Therefore, the function takes precedence over the class.
As mentioned in the comments, the class is still accessible via the class
or struct
keyword. If the class took precedence, the function would be unreachable.
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