Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

members of a class known at any point inside class

Tags:

c++

I always thought that if I declare member of a class inside class this member is known at the entire scope of a class that is:

 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.

Anyhow this doesn't because I'm getting error that v_ isn't known

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

Would be glad to learn why.

I'm using intel compiler v14 SP1

Thank you.

like image 490
There is nothing we can do Avatar asked Aug 26 '14 18:08

There is nothing we can do


2 Answers

3.3.7 Class scope

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

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

...

That 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 shall compile

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

but not the second example in your original post.

like image 101
AnT Avatar answered Sep 28 '22 06:09

AnT


Your code compiles with Clang.

Reading C++11 specifications you are not allowed to declare the variable after it is being used as function/constructor parameter.

like image 23
CoffeDeveloper Avatar answered Sep 28 '22 07:09

CoffeDeveloper