Is this allowed?
Class A{
...
...
};
A a; //Global object
int main()
{
A a; // Local object
.
.
.
.
return 0;
}
Here a global object has been declared after the class definition, but also a local variable has been declared. Is it ok? Why?
It's perfectly legal to "hide" the declaration of an object, with another declaration in tighter scope. Within your main function, a will refer to the local variable. Outside the main function, a will refer to the global variable.
As to whether it's "ok" - I would say "no". It's a bad idea, in that it's likely to make your code confusing, and more prone to accidentally introducing bugs. I wouldn't advise doing it.
Keep in mind that although you could theoretically access two variables, when one of them is shadowed, it is impossible to juggle three.
#include <iostream>
int a = 1;
int main()
{
int a = 2;
{
std::cout << a; // 2
std::cout << ::a; // 1
int a = 3;
std::cout << a; // 3
std::cout << ::a; // 1
// there is no way to get to a that has 2 written in it
// that is until we reach the closing curly brackets below
}
}
When you see the code that has shadowing in it, this usually points to a programmer's inability to name variables well. Each variable should be as descriptive as possible, without being excessively long.
Although is Syntatically correct and compiler will have no problem compiling this code, because when you will access a
inside main
it will refer to the local copy, and outside main
it will refer to the global one.
But this style of coding, using same name for local and global variables is bad idea, because it is very confusing for others to read, and if the code is large, even you will find it difficult to track it.
I agree with other posts here. It's not a good idea but occasionally it does crop up. You can use the global scope operator to access a variable of the same name outside of local scope.
I.e using '::a' inside your main function will actually access the global scope version of 'a', not local scope.
This is correct because
operating system needs to know scope of variables. If a variable is local then that variable should be destroyed as program goes out of the scope of that function while global variables should not be destroyed until or unless program exits . For this purpose global variables are stored in heap and local variables are stored in stack . You can do this but it is not okay as it makes your code only confusing if you write a code containing large amount of classes and global variables with same name .