Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access private data members outside the class without making "friend"s? [duplicate]

I have a class A as mentioned below:-

class A{
     int iData;
};

I neither want to create member function nor inherit the above class A nor change the specifier of iData.

My doubts:-

  • How to access iData of an object say obj1 which is an instance of class A?
  • How to change or manipulate the iData of an object obj1?

Note: Don't use friend.

like image 581
Abhineet Avatar asked Jul 16 '11 11:07

Abhineet


People also ask

Is there a way to access private members outside a class?

Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.

Can we access private data members of class outside without using a friend function?

So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers.

Can private members be accessed using friend functions?

A friend function cannot access the private and protected data members of the class directly. It needs to make use of a class object and then access the members using the dot operator. A friend function can be a global function or a member of another class.


1 Answers

Here's a way, not recommended though

class Weak {
private:
    string name;

public:
    void setName(const string& name) {
        this->name = name;
    }

    string getName()const {
        return this->name;
    }

};

struct Hacker {
    string name;
};

int main(int argc, char** argv) {

    Weak w;
    w.setName("Jon");
    cout << w.getName() << endl;
    Hacker *hackit = reinterpret_cast<Hacker *>(&w);
    hackit->name = "Jack";
    cout << w.getName() << endl;

}
like image 83
Sleiman Jneidi Avatar answered Oct 05 '22 07:10

Sleiman Jneidi