access c++ private data members without using the " Friend" type
main() can be a friend function?

Recommended Answers

All 16 Replies

maybe use get and set functions? If you're doing it without friends, it seems like making main a friend is not allowed...

>access c++ private data members without using the " Friend" type
Why is this such a common question? It's insanely stupid.

I'm just learning C++ myself...

Wouldn't you use a public member function to access and modify private member variables?

> Wouldn't you use a public member function to access and modify private member variables?
Yes everyone else would.

But some people seem to like asking stupid questions like this which subvert the whole idea of using an OO language for data encapsulation.

Like somehow knowing that if you could smash your way through the barriers, it would make you some kind of 'leet' programmer (it won't).

I'm just learning C++ myself...

Wouldn't you use a public member function to access and modify private member variables?

Indeed, also you can use "friend" functions to classes - as indicated above. Example:

class simple {
friend void fac(simple *ptr);
public:
protected:
private:
string stest;
};
void fac(simple *ptr) {
ptr->stest = "Hello";
cout << ptr->stest << endl;
}
int main() {
simple test;
fac(&test);
return 0;
}

Hope I've helped, LamaBot

Indeed, also you can use "friend" functions to classes - as indicated above. Example:
...

Yes, but the thread was about changing private variables without using friends. ;)

He had a question, I thought I'd answer and add to it. I might need his help one day.

LamaBot

> Wouldn't you use a public member function to access and modify private member variables?
Yes everyone else would.

But some people seem to like asking stupid questions like this which subvert the whole idea of using an OO language for data encapsulation.

Like somehow knowing that if you could smash your way through the barriers, it would make you some kind of 'leet' programmer (it won't).

I really don't have words. How to put it...??? If your petty brain can't think of a usecase for this ASK. Don't profess there is no such usecase. Have you heard of things like "real world programming", "customer faults" "work arounds".. ??? I don't think so. May be if you knew at least one of these things you won't be talking in this language..

>access c++ private data members without using the " Friend" type
Why is this such a common question? It's insanely stupid.

If you donno the answer, just say so.. The way you dismiss it, looks like you know at least 5-10 solutions to the problem...

Now before you both start let me give you the usecase(s).
1. During you coding you realize some problem with your design and need to access the private member variable of someone else's class from yuor code, but you don't have the time/authority to convince the provider to change his/her code.
2. You have an urgent bug to be corrected. For this you need to access a private member variable of some class. But if you change that class you will have to recompile and patch all other components that depend on this class. This would take time/testing and most of all co-ordination with other component owners.
3. You have to do unit testing and for this you're writing some stub, as per the guidelines you are NOT supposed to make copies of interface classes' header files for stubbing so you gotta change the value of a private variable in your stub from your driver (even though the variable is private and driver is not a friend)

@virsa
Coming to solution. I hope get/set methods is something you already knew.. !
There are at least 3 other ways (I know of)
1. If you know the object layout, you can add appropriate offset to the pointer to an object of this type to get a simple pointer to the member variable (which will be exempt from all access checks by compiler)
2. Say the header file of your class that has this private member is provider.h. Add #define private public before including it:

#define private public
#include "provider.h"
#undef private

int main()
{
      provider obj;
      obj.private_member_variable = "new value";
      return 0;
}

3. Let me leave his out for now and let ther other experts answer this.. ! I suppose they can give at least a few more...

commented: Don't be rude if you don't know what you're talking about. -1

Heh, the reason Narue and Salem were so abrubt with their responses is because the OP's question is basically asking "how to I break the rules for OOP without getting in trouble?" The answer that will usually work is to have get/set methods. Sometimes that isn't quite what you want, and you use a friend, but the OP specified that friends weren't allowed.

1. If you know the object layout, you can add appropriate offset to the pointer to an object of this type to get a simple pointer to the member variable (which will be exempt from all access checks by compiler)

This requires you to know how the compiler will lay the data out in memory, plus a bit of ugly hacking. Not a good solution.

2. Say the header file of your class that has this private member is provider.h. Add #define private public before including it:

Horrible idea. There's a reason for having private members, making them public is a very bad idea.

[edit:] by the way, Narue is very much an expert, and highly respected on the forum. She just has a sharp wit :p

> If your petty brain can't think of a usecase for this ASK. Don't profess there is no such usecase.
Gee, ya think there might be something fundamentally WRONG with your design if you have to resort to this kind of crap?

> #define private public
In other words, completely forget about pretending to program in C++, and use something called 'Super C'

> This would take time/testing and most of all co-ordination with other component owners.
And poking away at the innards of some class doesn't need testing - boggle!!!!
I'm glad you're nowhere near any code I'm responsible for.

What are you going to do after the change?
Implement it properly with a proper access method?
Or leave it to fester with all your other quick fix hacks until the whole sorry mess falls apart.

Heh, the reason Narue and Salem were so abrubt with their responses is because the OP's question is basically asking "how to I break the rules for OOP without getting in trouble?" The answer that will usually work is to have get/set methods. Sometimes that isn't quite what you want, and you use a friend, but the OP specified that friends weren't allowed.
>> Indeed breaking the rules of OO is a horrible thing. But that doesn't mean that there are cases in real life when you are forced to do that.

This requires you to know how the compiler will lay the data out in memory, plus a bit of ugly hacking. Not a good solution.
>> True That's why I wrote "If you know the object layout..."
Horrible idea. There's a reason for having private members, making them public is a very bad idea.
>> NONE of these solutions should be implemented given a choice. They are all horrible. One should do proper OO design, encapsulation, get/set methods, insulation as/if/when you need, BUT IF YOU HAVE A CHOICE.

by the way, Narue is very much an expert, and highly respected on the forum. She just has a sharp wit :p
>> As can be seen I'm a newbi poster. Sorry to Narue. Just that she could have as well given the answer/link-to-answer and said "don't do this at home".

---------------------------------
Gee, ya think there might be something fundamentally WRONG with your design if you have to resort to this kind of crap?
>> Of course there is something fundamentally WRONG with your design ! There is no question abt it, but WHAT IF you can't change the design and need a "quick fix" to satisfy the customer and honor your SLA?? That's the whole point.

In other words, completely forget about pretending to program in C++, and use something called 'Super C'
>> Again I never said ANY of these solutions should be implemented given a choice. Do proper OO design, encapsulation, get/set method, insulation if you need, IF YOU HAVE A CHOICE.

And poking away at the innards of some class doesn't need testing - boggle!!!!
>> Of course it needs, but only in the user component not ALL. That means less time, faster patch.

I'm glad you're nowhere near any code I'm responsible for.
>> Given the amount you brag I would be very interested in seeing this "any code I'm responsible for".

What are you going to do after the change?
Implement it properly with a proper access method?
>> OF COURSE YES ! Is there a question abt it? Who in their right frame of mind would like to have some crap code like this in their customer realse for long ?!

>> Finally how abt you at least give few solutions to the problem?

---------------------------------
Guys, you got the attitude from me simply coz you gave some. If it was out of place, please do forgive me.
But you are the experts so be like them. There is a say in my language (Gujarati) "When mongos grow on a mango tree, the tree bows down (NOT UP)."

>Indeed breaking the rules of OO is a horrible thing. But that doesn't mean that there are cases in real life when you are forced to do that.
Until we run into such a situation, let's not worry about it, OK? The point of this (homework?) was to learn how to use public accessor methods to modify the private internals, NOT to hack some C++ keywords using preprocessor directives.

>NONE of these solutions should be implemented given a choice.
Then why talk about them in the first place, save for educating the person on what not to do?

>she could have as well given the answer/link-to-answer and said "don't do this at home"
If I was discussing how to flush the input buffer, I could explain that you can do it like this:

fflush(stdin); // dont do this at home

What am I saying with such a statement? Wouldn't it be better to explain proper methods?

>Indeed breaking the rules of OO is a horrible thing. But that doesn't mean that there are cases in real life when you are forced to do that.
Until we run into such a situation, let's not worry about it, OK? The point of this (homework?) was to learn how to use public accessor methods to modify the private internals, NOT to hack some C++ keywords using preprocessor directives.

I'm a bit surprised that people (which would include you) prefer following:
" Why is this such a common question? It's insanely stupid."
or
" Yes everyone else would. But some people seem to like asking stupid questions like this..."

rather than saying:
"don't do such things, it's not good because..."
or
"why do you ask, coz solutions to this problem are not supposed to be good for programming..."

thekashyap, if you haven't already, I suggest you read though this page, especially this section.

Thanks. I hadn't. I did.

So let me cut the crap n come to the point.
Third solution:
Basic requirement for this solution to work is that the provider class must be available in a .a or .so.
We misuse the fact compiler knows "private" linker doesn't. Just open the provider.h and make the member public. Compile your code that uses this member variable with this new header. Link with the original .a or .so file. Run... :)

Example:
$ cat client.cxx

#include "provider.h"

int main()
{
        provider p ;
        p.private_member = 10 ;

        return 0 ;
}

$ cat provider.h

class provider {

public:
        provider() ;
        ~provider() ;

        void some_method() ;

private:
        int private_member ;

};

$ cat provider.cxx

#include "provider.h"
#include <iostream>

using namespace std ;

provider::provider()
{ cout << "inside provider() private_member = " << private_member << endl; }

provider::~provider()
{ cout << "inside ~provider() private_member = " << private_member << endl; }

void provider::some_method()
{ cout << "inside provider::some_method()" << endl ; }

$ CC -G -o libprovider.so provider.cxx
$ <comment out line 9 in provider.h>
$ CC -c client.cxx
$ CC client.o -lprovider -o out
$./out
inside provider() private_member = 0
inside ~provider() private_member = 10
$ CC -V
CC: Sun WorkShop 6 update 2 C++ 5.3 Patch 111685-15 2003/05/14
$

access c++ private data members without using the " Friend" type
main() can be a friend function?

its against OOP concept but still... this might help

class A { 
private:
int a;
char b;
public:
A(): a(1), b('A') {}
};
int main() 
{
A* obj = new A();;
int* pInt = reinterpret_cast<int*>(obj);
cout<<*pInt<<endl;
++pInt;
cout<< *reinterpret_cast<char*>(pInt) <<std::endl;

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.