Class members known at any point within the class

I always thought that if I declare a member of a class inside a class, this member is known throughout the scope of the class, which:

class X { public: X(int a) :v_(a) {} private: int v_;//even though v_ is declared here I'm using it in ctor which is above this line }; 

So that makes sense to me.

In any case, this is not because I get an error that v_ not known.

 class X { public: X(decltype(v_) a) :v_(a)//error on this line, compiler doesn't know v_ {} private: int v_; }; 

I would be glad to know why.

I am using intel compiler v14 SP1

Thanks.

+5
source share
3 answers

3.3.7. Class scope

1 The following rules describe the scope of names declared in classes.

1) The potential domain of the name declared in the class consists not only of the declarative region following the name of the declaration point, but also of all function bodies, sliding or equal initializers of non-static data members and default arguments in this class (including such things in nested classes).

...

This means that you can use v_ in function bodies, constructor initializer lists, and default arguments. You are not allowed to use v_ in parameter declarations the way you used it in your code.

For example, this should compile

 class X { public: X(int a = decltype(v_)()) : v_(a) {} private: int v_; }; 

but not the second example in your original post.

+6
source

Your code is compiled using Clang.

Reading C ++ 11 specs, you are not allowed to declare a variable after it is used as a function / constructor parameter.

+1
source

In many cases, classes, including function signatures, will be defined in headers, and in bodies in cpp files. Since the header will be read by the compiler at the beginning of reading the cpp file, this problem usually does not occur. But really, C ++ compilers do not look to the future.

-1
source

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


All Articles