In the following example, will the size of array v
guaranteed to be 2 or 3?
static const int i = 3;
class X {
char v[i];
static const int i = 2;
};
From the standard,
3.3.6/2 A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S
I think this means 'i' shall be 2
and what does the re-evaluation thing really means here?
A class's members include all the members declared in the class, along with all members (except constructors and finalizers) declared in all classes in its inheritance hierarchy. Private members in base classes are inherited but are not accessible from derived classes. Fields are variables declared at class scope.
An object has function prototype scope if its declaration appears within the list of parameters in a function prototype. A class member has class scope if its declaration is located inside a class.
Member functions execute on an object of that class. Most classes have two types of member functions: accessor functions: these allow the user to get data from the object. mutator functions: these allow the user to set data in the object.
1. Which is private member functions access scope? Explanation: The member functions can be accessed inside the class only if they are private. The access is scope is limited to ensure the security of the private members and their usage.
The correct behavior is that it should cause an error because re-evaluation would change the meaning:
Example from section 3.3.6:
The potential scope of a declaration that extends to or past the end of a class definition also extends to the regions defined by its member definitions, even if the members are defined lexically outside the class (this includes static data member definitions, nested class definitions, member function definitions (including the member function body and, for constructor functions (12.1), the ctor-initializer (12.6.2)) and any portion of the declarator part of such definitions which follows the identifier, including a parameter-declaration-clause and any default arguments (8.3.6). [Example:
The example is similar to yours (using enum
instead of a static const int
):
typedef int c;
enum { i = 1 };
class X {
char v[i]; // error: i refers to ::i
// but when reevaluated is X::i
int f() { return sizeof(c); } // OK X::c
char c;
enum { i = 2 };
};
At the time v[i]
is encountered, the compiler only knows about enum { i = 1 };
(or static const int i = 3;
, but when the full class declaration is known, char v[i]
would be different because i
would be re-evaluated to 2
.
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