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

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.

This question is related to c++ class private encapsulation data-members

The answer is


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


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


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

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;

}

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

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.


There's no legitimate way you can do it.


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.


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.


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.


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

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

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to private

Private class declaration Python read-only property What is the use of a private static variable in Java? How to access private data members outside the class without making "friend"s? JUnit Testing private variables? What are access specifiers? Should I inherit with private, protected or public? Do subclasses inherit private fields? What is the difference between public, private, and protected? Internal vs. Private Access Modifiers Private Variables and Methods in Python

Examples related to encapsulation

What's the difference between abstraction and encapsulation? How abstraction and encapsulation differ? Simple way to understand Encapsulation and Abstraction Difference between Encapsulation and Abstraction How to access private data members outside the class without making "friend"s? Set and Get Methods in java? Good way to encapsulate Integer.parseInt() Difference between private, public, and protected inheritance Difference between abstraction and encapsulation? Why are Python's 'private' methods not actually private?

Examples related to data-members

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