user103214
user103214

Reputation: 3668

Scope of members in class

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?

Upvotes: 7

Views: 988

Answers (2)

Vladimir Barshak
Vladimir Barshak

Reputation: 15

Array size should be 3 in this case. If you look in your code line by line. Compliler know nothing about X::i when construct array. If you change lines inside class when size of array become 2 and second i will hide first.

Upvotes: 1

wkl
wkl

Reputation: 80041

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.

Upvotes: 4

Related Questions