Is it possible to declare a pointer to private data member of a class? If so, how do you do it?
So, in order to make your pointer to point to a private data member of a class you have to initialize that pointer (or assign to it) in an area where that private data member is accessible: inside a method of the owning class or inside a friend function. Show activity on this post.
The catch is, of course, that since the member is private, you can only create the pointer inside the class, where you can see the member.
When someone says "declare a pointer to something ", they are usually talking about type-related attributes of a pointer, as in "declare a pointer to int ". The property of being private does not affect the type of a member at all, meaning that a member of type int is always just a member of type int, regardless of whether it is public or private.
When you say "a pointer to data member of a class", it is not clear what kind of pointer you are talking about: ordinary or pointer-to-member. However, the above still applies to both kinds: both can easily point to public, protected or private members of the class.
Yes, and the same way you would create any other pointer. The catch is, of course, that since the member is private, you can only create the pointer inside the class, where you can see the member.
class A
{
public:
int* getFooPtr()
{
return &foo; // OK; Inside the class foo is visible
}
private:
int foo;
};
int main()
{
A a;
int* p_foo1 = &a.foo; // Illegal; Outside the class, foo is private
int* p_foo2 = a.getFooPtr(); // OK; getFooPtr() is a public member function
}
So it's possible to create pointers to private members, but only inside the class' member functions, and it is possible to return those created pointers from member functions. Whether or not it's a good idea to return pointers to private members is another question entirely (usually it's not a good idea).
You can access outside of the declaring class any non-static private member if you are exploiting the fact that C++ allows you to pass the address of the private member in explicit instantiation. However you won't be able to access static private members, since you have to use a pointer to member with this technique.
struct A
{
A() : x("proof!") {}
private:
char const* x;
};
template class stow_private<A_x,&A::x>;
int main()
{
A a;
// Use the stowed private member pointer
std::cout << a.*stowed<A_x>::value << std::endl;
};
You can find the implementation of stowed<>
and details here:
http://bloglitb.blogspot.hu/2010/07/access-to-private-members-thats-easy.html and
https://gist.github.com/dabrahams/1528856
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With