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

121,048

Solution 1

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

Solution 2

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;

}

Solution 3

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

Solution 4


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

Solution 5

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.

Share:
121,048
Abhineet
Author by

Abhineet

Learner.

Updated on July 23, 2022

Comments

  • Abhineet
    Abhineet almost 2 years

    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.

  • Abhineet
    Abhineet almost 13 years
    But we can use making friend of class A.
  • iammilind
    iammilind almost 13 years
    I dont want to create member function for above class A. Also your A::doSomething() is private. This code results in compile error.
  • iammilind
    iammilind almost 13 years
    This can result in undefined behavior. Not portable.
  • Alok Save
    Alok Save almost 13 years
    @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.
  • Ajay
    Ajay almost 13 years
    Absolutely! Inherit from other class, change pragma, add virtual functions, make it a union - I didn't say it was correct!
  • iammilind
    iammilind almost 13 years
    I haven't downvoted your answer. It was a string of downvotes to may answers.
  • treecoder
    treecoder almost 13 years
    friend friend ... my friend :)
  • Ajay
    Ajay almost 13 years
    Never-mind. I was sure I would get a down-vote! :)
  • Mat
    Mat almost 13 years
    The question reads: Please note: I dont want to use friend.
  • Alok Save
    Alok Save almost 13 years
    @Downvoters: Any explanations for your downvotes?
  • Abhineet
    Abhineet almost 13 years
    I have clearly mentioned above that i dont want to change the behaviour.
  • Abhineet
    Abhineet almost 13 years
    @greengit: there is a worth in it, i have clarified my doubt. Atleasst for me it means a lot my friend. :)
  • Alok Save
    Alok Save almost 13 years
    @RocketR: +1, to compensate downvotes for a Q that was edited and modified later on.
  • Abhineet
    Abhineet almost 13 years
    @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
    Alok Save almost 13 years
    @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.
  • v.oddou
    v.oddou almost 8 years
    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
  • frp farhan
    frp farhan over 7 years
    Alexander your code is not working.
  • EmpathicSage
    EmpathicSage almost 7 years
    I fixed the compilation issue with the example
  • Adrian W
    Adrian W almost 6 years
    @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
    v.oddou almost 6 years
    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
  • xaxxon
    xaxxon over 5 years
    "You can't" - so you're saying this is incorrect and/or UB? bloglitb.blogspot.com/2011/12/…
  • Mat
    Mat over 5 years
    @xaxxon: that code uses a friend-based trick.
  • xaxxon
    xaxxon over 5 years
    @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
    Mat over 5 years
    @xaxxon: This question is about private access without using friend. Your article uses friend.
  • xaxxon
    xaxxon over 5 years
    @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.
  • dialer
    dialer about 4 years
    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.
  • Zenul_Abidin
    Zenul_Abidin over 2 years
    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 = /* ... */;