Access to variables with the same name in different areas

WITH

#include <iostream> using namespace std; int a = 1; int main() { int a = 2; if(true) { int a = 3; cout << a << " " << ::a // Can I access a = 2 here? << " " << ::a << endl; } cout << a << " " << ::a << endl; } 

with exit

 3 1 1 2 1 

Is there a way to access 'a', equal to 2 inside the if statement, where there is an "a", equal to 3, with the output

 3 2 1 2 1 

Note I know this should not be done (and the code should not go to the point where I need to ask). This question is more "can it be."

+4
source share
2 answers

No, you cannot, (2) is hidden.

Ref: 3.3.7 / 1

A name can be hidden explicitly declaring the same name in a nested declarative region or derived class (10.2).

Reference: 3.4.3 / 1

The name of the class or namespace member can be specified after: the domain resolution operator (5.1) is applied to the nested qualifier name that assigns its class or namespace. When searching for a name preceding the scope statement, the names of objects, functions, and enumerators are ignored. If the name is not found in the class name (clause 9) or namespace-name (7.3.1), the program is poorly formed.

+8
source

The short answer is no. You basically redefine the inherited area locally, and it will use that local copy over any inherited ones.

Basically, as a child object that overrides the function or variable of the parent object, it will use it in copies, regardless of what the parent had.

0
source

Source: https://habr.com/ru/post/1342208/


All Articles