Here's some code for example
class A {
int i;
}
void main()
{
A a;
}
Is there any possible (probably hackish) way to access a::i
in main
?
Edit:
a::i
is supposed to stay private.
Here's some code for example
class A {
int i;
}
void main()
{
A a;
}
Is there any possible (probably hackish) way to access a::i
in main
?
Edit:
a::i
is supposed to stay private.
*reinterpret_cast<int*>(&a) = 666;
That should do the trick.
Now, technically you're causing UB by using a post reinterpret_cast variable when the types are different. But, i
is guaranteed to be at the beginning of A
because A
is a POD.
This will absolutely not work if there are virtual functions and is not guaranteed to if you have custom constructors.
YOU SHOULD NOT EVER DO ANYTHING REMOTELY LIKE THIS!!
A very hackish way that I've used for unit testing is (WARNING: only use under adult supervision):
// In your unit test only
#define class struct
#define private public
Put this in a header file that's only used for unit testing!
EDIT: (thanks to @Peter) And only use this for quick and dirty testing - NEVER check this into a repository!
For sure this is not guaranteed to work, but it will probably work on most platforms:
#include <iostream>
class A {
int i;
public:
A (int j) : i(j) { ; }
};
int awfulGetI(A const& a);
int main()
{
A a(3);
int j = awfulGetI(a);
std::cout << "a.i=" << j << std::endl;
}
// Ugly code that may or may not work here:
struct AA {
int i;
};
int awfulGetI(A const& a)
{
struct AA const* p = reinterpret_cast<AA const*>(&a);
return p->i;
}
When creating classes, usually the point is to have the encapsulation that they provide (though, of course, you may need to retrieve or mutate the values therein). There is always the possibility of using the memory address as is demonstrated in a couple of answers here, but have you considered creating a public "getter" function in your class that simply returns the value of the variable (since the function itself has access)?
Ex.
class A {
// private:
int i = 7;
// default value used for illustration purposes.
// public:
public int getInt()
{
return i;
}
}
int main() {
A a;
int x = a.getInt(); // when called, getInt() should return 7 (in this case).
cout << x; // just to check.
return 0;
}