c++ --direct-- access of class members in non-member function bodies

1.6k views Asked by At

The following example is obviously wrong, but I would like to know if it possible to achieve something like the following

extern int return_value();

class A {
private:
    int k = 1;
public:
    friend int return_value();
};

int return_value()
{
    return k;
}

I know I can't do the following without passing an instance of class A into function return_value() as return_value(A &a) then accessing the variable as a.k

note the function return_value() is an example. I would like to know if there is a way within the scope of the C++ language to allow direct access to variables in non-member function bodies

1

There are 1 answers

0
Abhishek Bansal On

AFAIK there are only two ways to access members of a class (for non-member functions).

  1. Either through an instance as you described.
  2. Or without the instance iff the member is declared as a static member. That is, it has the same value for all objects of that class, and can be accessed directly using the class scope operator.

Ofcourse this is assuming the scope permits the function to access the class members.