By Abhineet


2011-07-16 11:54:46 8 Comments

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.

12 comments

@Sleiman Jneidi 2011-11-27 00:10:54

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;

}

@Alexander Drichel 2013-03-14 16:12:40

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;
}

@frp farhan 2016-09-21 11:32:23

Alexander your code is not working.

@Zahnon 2017-06-21 00:34:57

I fixed the compilation issue with the example

@NEURON ENIX 2016-09-18 17:24:40

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.....";
}

@GIFT.azib 2013-04-23 04:47:46

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();
}

@Timmah 2011-11-15 20:45:27

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.

@v.oddou 2016-06-30 08:44:11

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.pdf

@Adrian W 2018-06-18 20:27:59

@v.oddou 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.

@v.oddou 2018-06-19 02:37:28

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 LLOL

@Alok Save 2011-07-16 11:58:42


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;
}

@Abhineet 2011-07-16 12:01:01

But we can use making friend of class A.

@iammilind 2011-07-16 12:04:47

I dont want to create member function for above class A. Also your A::doSomething() is private. This code results in compile error.

@Alok Save 2011-07-16 12:08:23

@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.

@Alok Save 2011-07-16 12:17:44

@Downvoters: Any explanations for your downvotes?

@RocketR 2011-07-16 11:59:48

There's no legitimate way you can do it.

@Abhineet 2011-07-16 12:39:06

I have clearly mentioned above that i dont want to change the behaviour.

@Alok Save 2011-07-16 12:54:34

@RocketR: +1, to compensate downvotes for a Q that was edited and modified later on.

@Abhineet 2011-07-16 13:01:55

@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...

@Alok Save 2011-07-16 13:03:51

@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.

@n. 'pronouns' m. 2011-07-16 12:14:57

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.

@iammilind 2011-07-16 11:58:19

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.

@Ajay 2011-07-16 11:59:30

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;
}

@iammilind 2011-07-16 12:06:37

This can result in undefined behavior. Not portable.

@Ajay 2011-07-16 12:11:14

Absolutely! Inherit from other class, change pragma, add virtual functions, make it a union - I didn't say it was correct!

@iammilind 2011-07-16 12:13:15

I haven't downvoted your answer. It was a string of downvotes to may answers.

@Ajay 2011-07-16 12:15:56

Never-mind. I was sure I would get a down-vote! :)

@Mat 2011-07-16 11:57:21

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.)

@treecoder 2011-07-16 12:14:08

friend friend ... my friend :)

@Mat 2011-07-16 12:17:24

The question reads: Please note: I dont want to use friend.

@Abhineet 2011-07-16 12:49:22

@greengit: there is a worth in it, i have clarified my doubt. Atleasst for me it means a lot my friend. :)

@xaxxon 2018-09-03 22:10:11

"You can't" - so you're saying this is incorrect and/or UB? bloglitb.blogspot.com/2011/12/…

@Mat 2018-09-04 04:56:13

@xaxxon: that code uses a friend-based trick.

@xaxxon 2018-09-04 17:54:19

@Mat 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.

@Mat 2018-09-05 04:59:22

@xaxxon: This question is about private access without using friend. Your article uses friend.

@xaxxon 2018-09-05 16:14:14

@Mat 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.

@James 2011-07-16 11:56:53

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.

Related Questions

Sponsored Content

7 Answered Questions

9 Answered Questions

[SOLVED] How to print instances of a class using print()?

24 Answered Questions

[SOLVED] Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

11 Answered Questions

[SOLVED] How to read the value of a private field from a different class in Java?

9 Answered Questions

[SOLVED] Testing private class member in C++ without friend

1 Answered Questions

[SOLVED] How to access member function of the private object?

  • 2017-05-13 14:44:48
  • Di Miao
  • 60 View
  • -4 Score
  • 1 Answer
  • Tags:   c++ class private

5 Answered Questions

6 Answered Questions

3 Answered Questions

[SOLVED] C++ Friend Function Does Not Have Access To Private Member

4 Answered Questions

[SOLVED] Accessing private members in a class

Sponsored Content