Monte
Monte

Reputation: 39

How is the friend function accessed in the case of accessing private class member?

This is a tricky tactic to access a private member of class. But I can't get the point of declaration of friend get inside struct A_member?

#include <iostream>

struct A {
private:
  int member;
};

template<typename Tag, typename Tag::type M>
struct Rob { 
  friend typename Tag::type get(Tag) {
    return M;
  }
};

// tag used to access A::member
struct A_member { 
  typedef int A::*type;
  friend type get(A_member);
};

template struct Rob<A_member, &A::member>;

int main() {
  A a;
  a.*(get(A_member())) = 42; // write 42 to it
  std::cout << "proof: " << a.*get(A_member()) << std::endl;
}

According to the cppreference:

(only allowed in non-local class definitions) Defines a non-member function, and makes it a friend of this class at the same time.

The explicit instantiation of struct Rob has made the newly defined get a non-member function, in the closest namespace, i.e. global namespace here. So can it be accessed directly in the main?

I suppose that the get has been defined in the global namespace already by the explicit instantiation, thus I don't understand the purpose of the friend declaration of get in struct A_member. Without this line, compiling gets error:

struct A_member { 
  typedef int A::*type;
  // friend type get(A_member);
};
<source>: In function 'int main()':
<source>:25:7: error: 'get' was not declared in this scope; did you mean 'std::get'?

Back to the above code, it redeclare a friend get inside the struct A_member and then magically it works. What's the purpose of this friend declaration? Is there some special c++ rule that I missed?

Upvotes: 0

Views: 77

Answers (1)

TIrs
TIrs

Reputation: 1

#include <iostream>

class MyClass {
private:
    int privateData;

public:
    MyClass(int data) : privateData(data) {}

    // Declare a friend function
    friend void accessPrivateData(const MyClass& obj);
};

// Definition of the friend function
void accessPrivateData(const MyClass& obj) {
    // Access private member of MyClass
    std::cout << "Private Data: " << obj.privateData << std::endl;
}

int main() {
    MyClass myObject(42);
    accessPrivateData(myObject); // Accesses private data via the friend function
    return 0;
}

Upvotes: -2

Related Questions