#include <iostream>
#include <vector>
using namespace std;
typedef int UINT4;
class Hack
{};
Hack& operator <(Hack& a , Hack& b)
{
std::cerr << "1";
return a;
}
Hack& operator >(Hack& a, Hack& b)
{
std::cerr << "2";
return a;
}
int main()
{
Hack vector; // It SHOULD be OK!?
Hack UINT4; // It SHOULD be OK!?
Hack v;
Hack Hack; // It SHOULD be OK!?
Hack = v; // It SHOULD be OK!?
// Please stop to think for a moment: What will the following output?
vector<UINT4> v;
// Oh, my god! The whole world goes mad!
return 0;
}
Question : Can we have a variable name as one of the predefined class name in our program? Answer : Yes we can have it.
If you happen to use the same name for both a class/struct A and a variable/function A you have to use the struct / class keyword, because the compiler interprets all following occurrences of A as the variable/function and not the struct/class.
We can have a method name same as a class name in Java but it is not a good practice to do so. This concept can be clear through example rather than explanations. In the below example, a default constructor is called when an object is created and a method with the same name is called using obj. Main().
Answer: A constructor is a special kind of subroutine in a class. It has the same name as the name of the class, and it has no return type, not even void. A constructor is called with the new operator in order to create a new object.
Ever heard of the following? Please look close at the parameter types :)
int stat(const char *path, struct stat *buf);
What you have shown in your question really isn't too dramatic. You declare a variable name in a local scope, but the type names in your program are in global scope. I will show you some real pervert thing now:
int nooo = 0;
int main() {
int nooo = 0;
}
W00t? Why does C++ allow us to create two variables of the same name!?!
Alright, I was kidding. I will now introduce you into the real dark sides of messing with duplicate names. Consider what C++ allows us!
struct A {
int A; // noes!
};
A A; // another A!
In essence, this one is all for C compatibility :)
You're asking the question from the point of view or someone who very well knows that he is using a class name as a variable identifier : obviously, this isn't a best practice.
Now, let's take it the other way around : suppose you have no idea that there is a weird typedef int i;
in some obscure header file you are including. Would you expect it to break the following innocent code ?
int i = 0;
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