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

12

26

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.

Gerdi answered 16/7, 2011 at 11:54 Comment(8)
Can you change the declaration of that class at all?Incongruity
No i dont want to change the declaration of that class.Gerdi
It seems that in SO, you are verifying whether private access specifier works fine or not.Resign
@greengit: The question was for my awareness that whether we can do by some or other way or not.Gerdi
Sounds like 'How do I make it work if I don't want to change anything?'. Is it a legacy or third-party code which you can't change but you need to access that member?Dimissory
@RocketR: Anyone has answer for RocketR question? :)Gerdi
@Abhineet: Next time you post a Q, you post all your requirements/expectations at the time of asking and not change them once people start answering & down voting them for not noticing your edits. It is your responsibility as a Q poster to post a clear, concise Q.Lianaliane
@Als: Yes friend i am sorry for that. And thanks for your support.Gerdi
I
12

You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.

(You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)

Incongruity answered 16/7, 2011 at 11:57 Comment(8)
friend friend ... my friend :)Sandpit
The question reads: Please note: I dont want to use friend.Incongruity
@greengit: there is a worth in it, i have clarified my doubt. Atleasst for me it means a lot my friend. :)Gerdi
"You can't" - so you're saying this is incorrect and/or UB? bloglitb.blogspot.com/2011/12/…Centrifuge
@xaxxon: that code uses a friend-based trick.Incongruity
@Incongruity if it's not UB, then perhaps you would consider changing your answer - especially because it's the accepted answer and people may take it to be accurate without reading all the comments.Centrifuge
@xaxxon: This question is about private access without using friend. Your article uses friend.Incongruity
@Incongruity I guess you're technically right, but I would assume they meant not adding friend to the class where you want to get access. There's no reason to artificially limit what can be done outside the class.Centrifuge
W
41

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;

}
Weather answered 27/11, 2011 at 0:10 Comment(3)
Note -- If the class has a vtable (std::is_polymorphic<T>()) you need to declare an additional void * as the first member. Needless to say this is a dirty hack on top of another dirty hack - avoid doing it.Way
@Way Can you expand on this? Maybe edit the answer or make a new followup answer?Liberality
This violates the strict aliasing rule, which is undefined behavior.Rheostat
M
14

Bad idea, don't do it ever - but here it is how it can be done:

int main()
{
   A aObj;
   int* ptr;

   ptr = (int*)&aObj;

   // MODIFY!
   *ptr = 100;
}
Megillah answered 16/7, 2011 at 11:59 Comment(4)
This can result in undefined behavior. Not portable.Resign
Absolutely! Inherit from other class, change pragma, add virtual functions, make it a union - I didn't say it was correct!Megillah
I haven't downvoted your answer. It was a string of downvotes to may answers.Resign
Never-mind. I was sure I would get a down-vote! :)Megillah
I
12

You can't. That member is private, it's not visible outside the class. That's the whole point of the public/protected/private modifiers.

(You could probably use dirty pointer tricks though, but my guess is that you'd enter undefined behavior territory pretty fast.)

Incongruity answered 16/7, 2011 at 11:57 Comment(8)
friend friend ... my friend :)Sandpit
The question reads: Please note: I dont want to use friend.Incongruity
@greengit: there is a worth in it, i have clarified my doubt. Atleasst for me it means a lot my friend. :)Gerdi
"You can't" - so you're saying this is incorrect and/or UB? bloglitb.blogspot.com/2011/12/…Centrifuge
@xaxxon: that code uses a friend-based trick.Incongruity
@Incongruity if it's not UB, then perhaps you would consider changing your answer - especially because it's the accepted answer and people may take it to be accurate without reading all the comments.Centrifuge
@xaxxon: This question is about private access without using friend. Your article uses friend.Incongruity
@Incongruity I guess you're technically right, but I would assume they meant not adding friend to the class where you want to get access. There's no reason to artificially limit what can be done outside the class.Centrifuge
L
10

EDIT:
Just saw you edited the question to say that you don't want to use friend.
Then the answer is:

NO you can't, atleast not in a portable way approved by the C++ standard.


The later part of the Answer, was previous to the Q edit & I leave it here for benefit of >those who would want to understand a few concepts & not just looking an Answer to the >Question.


If you have members under a Private access specifier then those members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    private:
        int c;
    public:
    void doSomething()
    {
        c = 10;    //Allowed 
    }
};

int main()
{
    MyClass obj;
    obj.c = 30;     //Not Allowed, gives compiler error
    obj.doSomething();  //Allowed
}

A Workaround: friend to rescue
To access the private member, you can declare a function/class as friend of that particular class, and then the member will be accessible inside that function or class object without access specifier check.

Modified Code Sample:

class MyClass
{
    private:
        int c;

    public:
    void doSomething()
    {
        c = 10;    //Allowed 
    }

    friend void MytrustedFriend();    
};

void MytrustedFriend()
{
        MyClass obj;
        obj.c = 10; //Allowed
}

int main()
{
    MyClass obj;
    obj.c = 30;     //Not Allowed, gives compiler error
    obj.doSomething();  //Allowed
    //Call the friend function
    MytrustedFriend();
    return 0;
}
Lianaliane answered 16/7, 2011 at 11:58 Comment(5)
But we can use making friend of class A.Gerdi
I dont want to create member function for above class A. Also your A::doSomething() is private. This code results in compile error.Resign
@iammilind: Can you not see public not being there a typo & well the answer in all completeness answers what options C++ provides. It also includes what fits his/her specification. I suggest you try having a broader view of things.Lianaliane
@Downvoters: Any explanations for your downvotes?Lianaliane
Would the second code example work if inside the friend function, you dereferenced the class to access the private member using the -> operator? e.g. MyClass* obj = /* ... */; obj->private_member = /* ... */;Mv
D
9

http://bloglitb.blogspot.com/2010/07/access-to-private-members-thats-easy.html

this guy's blog shows you how to do it using templates. With some modifications, you can adapt this method to access a private data member, although I found it tricky despite having 10+ years experience.

I wanted to point out like everyone else, that there is an extremely few number of cases where doing this is legitimate. However, I want to point out one: I was writing unit tests for a software suite. A federal regulatory agency requires every single line of code to be exercised and tested, without modifying the original code. Due to (IMHO) poor design, a static constant was in the 'private' section, but I needed to use it in the unit test. So the method seemed to me like the best way to do it.

I'm sure the way could be simplified, and I'm sure there are other ways. I'm not posting this for the OP, since it's been 5 months, but hopefully this will be useful to some future googler.

Definitive answered 15/11, 2011 at 20:45 Comment(3)
every single line of code to be exercised and tested oh my. that's bitterly stupid. rbcs-us.com/documents/Why-Most-Unit-Testing-is-Waste.pdfArlenaarlene
@Arlenaarlene Interesting article, but that's just an opinion. There are others. And of course these opinions are heavily disputed. We don't need to repeat that here. Just a question: when you refactor, how do you know you don't break things? I agree with Jim Coplien that "unit test" is not the answer to everything. But "not testing" is not a solution either.Optical
Of course I don't agree with everything in this article. eg the "1 trillionth" coverage, is rhetoric crap (because of recurrence relation that he conveniently swept under the carpet). What you say is also valid. Also he is stupidely idealistic: Tests should be designed with great care. Business people, rather than programmers LLOLArlenaarlene
C
5

In C++, almost everything is possible! If you have no way to get private data, then you have to hack. Do it only for testing!

class A {
     int iData;
};

int main ()
{
    A a;
    struct ATwin { int pubData; }; // define a twin class with public members
    reinterpret_cast<ATwin*>( &a )->pubData = 42; // set or get value

    return 0;
}
Crackdown answered 14/3, 2013 at 16:12 Comment(2)
Alexander your code is not working.Virescence
I fixed the compilation issue with the examplePycno
D
3

There's no legitimate way you can do it.

Dimissory answered 16/7, 2011 at 11:59 Comment(4)
I have clearly mentioned above that i dont want to change the behaviour.Gerdi
@RocketR: +1, to compensate downvotes for a Q that was edited and modified later on.Lianaliane
@Als: Earlier he has mentioned to do the following struct A{ int iData }; I have never told that i want to replace the keyword class with struct. And edition was to not to use friend not the other things...Gerdi
@Abhineet: Given the wide context of the Q that was put forward when it was posted, I would not discount that as an outright wrong answer.Lianaliane
R
2

Start making friends of class A. e.g.

void foo ();

class A{
  int iData;
  friend void foo ();
};

Edit:

If you can't change class A body then A::iData is not accessible with the given conditions in your question.

Resign answered 16/7, 2011 at 11:58 Comment(0)
D
2

iData is a private member of the class. Now, the word private have a very definite meaning, in C++ as well as in real life. It means you can't touch it. It's not a recommendation, it's the law. If you don't change the class declaration, you are not allowed to manipulate that member in any way, shape or form.

Depraved answered 16/7, 2011 at 12:14 Comment(0)
V
2

It's possible to access the private data of class directly in main and other's function...

here is a small code...

class GIFT
{
    int i,j,k;

public:
    void Fun() 
    {
        cout<< i<<" "<< j<<" "<< k;
    }

};

int main()
{
     GIFT *obj=new GIFT(); // the value of i,j,k is 0
     int *ptr=(int *)obj;
     *ptr=10;
     cout<<*ptr;      // you also print value of I
     ptr++;
     *ptr=15;
     cout<<*ptr;      // you also print value of J
     ptr++;
     *ptr=20; 
     cout<<*ptr;      // you also print value of K
     obj->Fun();
}
Venusberg answered 23/4, 2013 at 4:47 Comment(0)
M
1

friend is your friend.

class A{
    friend void foo(A arg);
    int iData;
};

void foo(A arg){
     // can access a.iData here
}

If you're doing this regularly you should probably reconsider your design though.

Monger answered 16/7, 2011 at 11:56 Comment(0)
T
-1

access private members outside class ....only for study purpose .... This program accepts all the below conditions "I dont want to create member function for above class A. And also i dont want to inherit the above class A. I dont want to change the specifier of iData."

//here member function is used only to input and output the private values ... //void hack() is defined outside the class...

//GEEK MODE....;)
#include<iostream.h>
#include<conio.h>

    class A
    {
    private :int iData,x;
    public: void get()             //enter the values
        {cout<<"Enter iData : ";
            cin>>iData;cout<<"Enter x : ";cin>>x;}

        void put()                               //displaying values
    {cout<<endl<<"sum = "<<iData+x;}
};

void hack();        //hacking function

void main()
{A obj;clrscr();
obj.get();obj.put();hack();obj.put();getch();
}

void hack()         //hack begins
{int hck,*ptr=&hck;
cout<<endl<<"Enter value of private data (iData or x) : ";
cin>>hck;     //enter the value assigned for iData or x
for(int i=0;i<5;i++)
{ptr++;
if(*ptr==hck)
{cout<<"Private data hacked...!!!\nChange the value : ";
cin>>*ptr;cout<<hck<<" Is chaged to : "<<*ptr;
return;}
}cout<<"Sorry value not found.....";
}
Tenebrous answered 18/9, 2016 at 17:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.