Amazon Interview Question
Software Engineer / DevelopersCountry: United States
+1 //access private member of an object without being friend
+2 #include<iostream>
+3 using namespace std;
+4
+5 class Base {
+6 int i;
+7 char j;
+8 public:
+9 Base(int one,char two):i(one),j(two) {}
+10 };
+11 int main()
+12 {
+13 Base *b=new Base(1,'a');
+14 void *v=(void*)b;
+15 int m=*(int*)v;
+16 cout<<"private member i="<<m<<endl;
+17 return 0;
+18
+19 }
I am able to modify the private value of the class.
if you can get your hands on a pointer/reference to a private member, you have full access to that member.
#include<iostream>
using namespace std;
class demo
{
private: int info;
public:
demo()
{
info=10;
}
void print_info()
{
cout<<info;
}
};
int main()
{
demo ob;
int* ptr=(int*)&ob;
*ptr=20;
ob.print_info();
return 0;
}
#include <iostream>
#include <cstdlib>
#include <cstring>
class X {
int x;
int y;
char* p;
public:
X() : x(0), y(0), p(0) {
}
~X() {
if(p)
free(p);
}
void SetP(const char* _p) {
size_t len = strlen(_p);
if(!p) {
p = static_cast<char*> (malloc(len));
} else {
p = static_cast<char*> (realloc(p, len));
}
memcpy(p, _p, strlen(_p));
}
const char* GetP() {
return p;
}
};
class Y {
public:
int x;
int y;
char* p;
public:
Y() : x(0), y(0), p(0) {
}
~Y() {
}
};
int main(int argc, char* argv[]) {
X x;
Y* y = reinterpret_cast<Y*>(&x);
// Y* y = (Y*) &x;
x.SetP("My Value");
std::cout << "V: " << y->p << std::endl;
}
Hope this works
#include <iostream>
#include <cstdlib>
#include <cstring>
class X {
int x;
int y;
char* p;
public:
X() : x(0), y(0), p(0) {
}
~X() {
if(p)
free(p);
}
void SetP(const char* _p) {
size_t len = strlen(_p);
if(!p) {
p = static_cast<char*> (malloc(len));
} else {
p = static_cast<char*> (realloc(p, len));
}
memcpy(p, _p, strlen(_p));
}
const char* GetP() {
return p;
}
};
class Y {
public:
int x;
int y;
char* p;
public:
Y() : x(0), y(0), p(0) {
}
~Y() {
}
};
int main(int argc, char* argv[]) {
X x;
Y* y = reinterpret_cast<Y*>(&x);
// Y* y = (Y*) &x;
x.SetP("My Value");
std::cout << "V: " << y->p << std::endl;
}
That seems like a really language specific question. With Java you can always use reflection, with C++ you can just directly read the bytes, since the concept of a private member can more accurately be defined as a contract than an actual restriction in C++
- Anonymous September 24, 2014