1

I have some c++ code that I am analyzing and I came across something I don't know what it means.

I have a class like this

class A
{
    public:
      int I;
      void function();
}

void A::function()
{
  cout << A::I;
}

Neither the function nor I is declared static in the class.

I don't understand the scope of I in the function. Is it the member of the instance that "function" is called from? Or is a static member? I've never seen the variable accessed in that manner from inside the class its a member from.

There is nothing to try, is a C++ specification question

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

3

This function

void function();

is a non-static member of the class.

You may use qualified names of members of the class like

void A::function()
{
  cout << A::I;
}

to distinguish members from for example local variables of a function.

Let's assume that the function is declared and defined like

void A::function( int I )
{
  cout << A::I + I;
}

In this function the parameter has the same name as the data member. You can write as shown above to distinguish the parameter and the data member or you could write

void A::function( int I )
{
  cout << this->I + I;
}

From the C++ 17 Standard (6.4.3.1 Class members)

1 If the nested-name-specifier of a qualified-id nominates a class, the name specified after the nested-namespecifier is looked up in the scope of the class (13.2), except for the cases listed below. The name shall represent one or more members of that class or of one of its base classes (Clause 13).

In the original function definition you can omit the class name because there is no ambiguity. The qualified name in this case is only used for documentation purpose.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335