c++ - Multiple Declaration error ignored in classes, why? -
consider following code fragment:
int test; //global variable class base { int test; //private member of base public: void getit() { cin>>test; } }; class derived: public base { public: void check() { test++; //neither access global test nor member of base } };
in above code, observe variable test
. first declared globally , again declared inside class in private scope.
my question first question how compiler allowing multiple declaration variable test
, why not giving error?
also, when function check()
tries access test
, compiler gives error. know private members not inherited , not accessible outside class, exists global variable, must accessible.
second question which test
present inside check()
whether global 1 or 1 declared inside class base
? also, how access global test
?
how compiler allowing multiple declaration variable test , why not giving error?
this basic tenet of c++'s scope rules. conceptually, it's no different declaring local variable same name global variable.
the test
in global namespace not conflict test
member variable (though 1 "hide" other when used in unqualified way, because member take priority during lookup).
this how language designed, , it's thing.
also, when function check() tries access test, compiler gives error.
the important thing consider precisely what error is. it's not telling no symbol test
can found; it's telling it's found member variable, , have no access it.
that tells access specifiers not affect visibility, accessibility:
your member test
still hides global test
, though can't access it.
to specify global test
, you'd need write ::test
.
Comments
Post a Comment