473,322 Members | 1,781 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Objects of the same class to access each other's private data

Hi,

I was wondering if there is any way to make two objects of the same
class to be able to access each other's private data, like this:

class A {
public:
void access( const A& a ) {cout<<"a.value="<<a.value<<endl; }
private:
int value;
};

There is of course the obvious solution to make the value public, but I
don't like that too much...

Cheers,
Manolis
Jul 23 '05 #1
12 2633
Why don't you just try to compile and run it?!

Jul 23 '05 #2
Yes, of course I've tried it; it doesn't work.

I just found a solution actually. Here it is (just in case someone else
wants it too):

class A {
public:
int add(const A& b) { return extaccess(*this,b); }
friend int extadd(const A& a, const A& b);
private:
int value;
};
int extadd( const A& a, const A& b )
{ a.value += b.value; return a.value; }

If someone has a nicer solution (apart from making the data public, or
having a public member to return the value) please let me know.

Manolis

__PPS__ wrote:
Why don't you just try to compile and run it?!

Jul 23 '05 #3
Manolis wrote:
Yes, of course I've tried it; it doesn't work.


It works fine for me, as it should. What was the error message that you got?

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #4
> I was wondering if there is any way to make two objects of the same
class to be able to access each other's private data, like this: class A {
public:
void access( const A& a ) {cout<<"a.value="<<a.value<<endl; }
private:
int value;
};


This compiles fine:

#include <iostream>

class A
{
public:
void access( const A& a)
{
std::cout << "a.value=" << a.value << std::endl;
}

private:
int value;
};

It is legal for two A's to access their private members. What error do
you get?

Jonathan

Jul 23 '05 #5
Manolis wrote:
Yes, of course I've tried it; it doesn't work.

I just found a solution actually. Here it is (just in case someone else
wants it too):

class A {
public:
int add(const A& b) { return extaccess(*this,b); }
friend int extadd(const A& a, const A& b);
private:
int value;
};
int extadd( const A& a, const A& b )
{ a.value += b.value; return a.value; }

If someone has a nicer solution (apart from making the data public, or
having a public member to return the value) please let me know.

Manolis

__PPS__ wrote:
Why don't you just try to compile and run it?!


Class data is often private. When access to private data
is required the class will normally have get and/or set
methods for the private data. Why don't you want to
take that approach?

Here's a simple example using 'private' data:

class A1
{
public:
A1(int val) : m_x(val) {}

int x() const { return m_x; }

int add(const A1& oth)
{
m_x += oth.x();
return m_x;
}

private:
int m_x;
};
Here's another example using 'protected' data:

class A2
{
public:
A2(int val) : m_x(val) {}

int add(const A2& oth)
{
m_x += oth.m_x;
return m_x;
}

protected:
int m_x;
};

Regards,
Larry

--
Anti-spam address, change each 'X' to '.' to reply directly.
Jul 23 '05 #6
Larry I Smith wrote:
Manolis wrote:
Yes, of course I've tried it; it doesn't work.

I just found a solution actually. Here it is (just in case someone else
wants it too):

class A {
public:
int add(const A& b) { return extaccess(*this,b); }
friend int extadd(const A& a, const A& b);
private:
int value;
};
int extadd( const A& a, const A& b )
{ a.value += b.value; return a.value; }

If someone has a nicer solution (apart from making the data public, or
having a public member to return the value) please let me know.

Manolis

__PPS__ wrote:
Why don't you just try to compile and run it?!


Class data is often private. When access to private data
is required the class will normally have get and/or set
methods for the private data. Why don't you want to
take that approach?

Here's a simple example using 'private' data:

class A1
{
public:
A1(int val) : m_x(val) {}

int x() const { return m_x; }

int add(const A1& oth)
{
m_x += oth.x();
return m_x;
}

private:
int m_x;
};
Here's another example using 'protected' data:

class A2
{
public:
A2(int val) : m_x(val) {}

int add(const A2& oth)
{
m_x += oth.m_x;
return m_x;
}

protected:
int m_x;
};

Regards,
Larry


Excuse me...

I guess I'm brain-dead today.

The A1::x() method is only necessary to allow
code and classes that are not members of class A1
access to the value of the 'm_x' variable.

Members of the same class can access each other's
'private' data.

Larry

--
Anti-spam address, change each 'X' to '.' to reply directly.
Jul 23 '05 #7

Larry I Smith wrote:
Class data is often private. When access to private data
is required the class will normally have get and/or set
methods for the private data. Why don't you want to
take that approach?

Don't you personally think it's stupid to write all the empty
getters/setters? May be it's easier to make them public then (if access
to private data required)? Private data should be private, meaning
object uses it for it's own private need and the user handles objects
by methods of the obect which in some way interact with the private
data.
Here's a simple example using 'private' data:

Such simple example may lead to conclusion that private and protected
aren't that usefull and force programmers to write extra code :), just
try to add substruct, multiply, and others ...
class A1
{
public:
A1(int val) : m_x(val) {}

int x() const { return m_x; }

int add(const A1& oth)
{
m_x += oth.x();
return m_x;
}

private:
int m_x;
};
Here's another example using 'protected' data:

class A2
{
public:
A2(int val) : m_x(val) {}

int add(const A2& oth)
{
m_x += oth.m_x;
return m_x;
}

protected:
int m_x;
};

Looks so cool - private and protected, what's the point in these two
pieces of code?? didn't you just copy-second A1 and replaced private
for protected? :)
Regards,
Larry

--
Anti-spam address, change each 'X' to '.' to reply directly.


Jul 23 '05 #8

Manolis wrote:
Yes, of course I've tried it; it doesn't work.
It works. Maybe you had some other problems.
example:

class a{
public:
void doit(const a& x){
a *p1 = this, *p2 = &x;
std::cout << (p1->a+p2->a) << std::endl;
}
private:
int a;
};

how different are the two pointers p1 and p2? If you couldn't access
private members of an instance of the same class then p1 also woudn't
be allowed to access ->a. Offcource compiler could deduce for this
simple example that p1 allows this access but not p2, but with a more
complicated case it might be impossible to do. So, obects have access
to private/protected members of objects of the same class, otherwise it
would be impossible to use p1->a in my example. All this is possible
because access rights are compile time checked.
I just found a solution actually. Here it is (just in case someone else wants it too):

class A {
public:
int add(const A& b) { return extaccess(*this,b); }
friend int extadd(const A& a, const A& b);
private:
int value;
};
int extadd( const A& a, const A& b )
{ a.value += b.value; return a.value; }

If someone has a nicer solution (apart from making the data public, or having a public member to return the value) please let me know.

Manolis

__PPS__ wrote:
Why don't you just try to compile and run it?!


Jul 23 '05 #9
> Larry I Smith wrote:
Class data is often private. When access to private data
is required the class will normally have get and/or set
methods for the private data. Why don't you want to
take that approach?
Don't you personally think it's stupid to write all the empty
getters/setters?


Be careful when you make statements such as "this is stupid".
May be it's easier to make them public then (if access
to private data required)? Private data should be private, meaning
object uses it for it's own private need and the user handles objects
by methods of the obect which in some way interact with the private
data.
No. Data should be private when it may be dangerous for the objet's
state to modify it without validation. What's more, using member
functions to access an aggregated object separates implementation from
interface. If the aggregated objet changes, the "accessor" may be able
to make it transparent. Allowing clients to use what is called
"implementation details" makes the object harder to modify.

I personally never use public data, except for very simple cases (such
as a point class). Using member functions allows me to control the
access and to separate between interface and implementation.
Here's a simple example using 'private' data:


Such simple example may lead to conclusion that private and protected
aren't that usefull and force programmers to write extra code :),

just try to add substruct, multiply, and others ...


More complex examples will not add anything to the problem and will
more probably confuse the original poster. Well-written, simple
examples, even if they don't depict the whole spectrum of the language,
are usually easier to comprehend.

This is for Larry I Smith:
class A1
{
public:
A1(int val) : m_x(val) {}

int x() const { return m_x; }

int add(const A1& oth)
{
m_x += oth.x();
This is unecessary. Different objects of the same class may access
their private and protected members directly.
return m_x;
}

private:
int m_x;
};

Here's another example using 'protected' data:
This example does not explain the use of protected data nor the
interaction between two objects using this features (such as a derived
class). I also do not understand why your first example uses a member
function to access 'm_x' and the following one does not.
class A2
{
public:
A2(int val) : m_x(val) {}

int add(const A2& oth)
{
m_x += oth.m_x;
return m_x;
}

protected:
int m_x;
};

Jonathan

Jul 23 '05 #10

Jonathan Mcdougall wrote:
Larry I Smith wrote:
Class data is often private. When access to private data
is required the class will normally have get and/or set
methods for the private data. Why don't you want to
take that approach?
Don't you personally think it's stupid to write all the empty
getters/setters?


Be careful when you make statements such as "this is stupid".


Sorry if it hurt you, I just remembered reading someone else's code
where for evry private member the author (probaly using macroses in
his/her text editor) put correstonding T getXXX(){return XXX;} void
setXXX(newXXX){XXX=newXXX;}. I think that person read somewhere that
it's good to have data members private :)
May be it's easier to make them public then (if access
to private data required)? Private data should be private, meaning
object uses it for it's own private need and the user handles objects
by methods of the obect which in some way interact with the private
data.


No. Data should be private when it may be dangerous for the objet's
state to modify it without validation. What's more, using member
functions to access an aggregated object separates implementation

from interface. If the aggregated objet changes, the "accessor" may be able to make it transparent. Allowing clients to use what is called
"implementation details" makes the object harder to modify.
I think you rephrased my short sentence about "Private data should be
private...". Imagine, the agregated obect is some sort of private data,
and the object that stores it provides some methods that in some way
iteract (or don't) with it's private data... I really didn't understand
some parts of your message about separated interface and
implementation, and transparent chage of aggregate...

I personally never use public data, except for very simple cases (such as a point class). Using member functions allows me to control the
access and to separate between interface and implementation.
Me too. I don't remeber when I used public data :)
A good example for public data would be complex numbers, where two
doubles (x,i) could be directly accessed. It would make sence to make
setters/getters for the two doubles only in case when we need to
calculate absolute value of the complex very often; In such case we
would have private member that stores absolute value and whenever x or
i gets new value we recalculate absolute value...
not sure if I'm right with termins. I meant absolute(complex) =
sqrt(x*x + i*i);

Here's a simple example using 'private' data:
Such simple example may lead to conclusion that private and protected
aren't that usefull and force programmers to write extra code :),

just
try to add substruct, multiply, and others ...


More complex examples will not add anything to the problem and will
more probably confuse the original poster. Well-written, simple
examples, even if they don't depict the whole spectrum of the

language, are usually easier to comprehend.

Well, example with complex numbers is really easy and tells where we
have benifit of using setters and private data.... Not only it has real
meaning (not like the A1 and A2 classes) but it's also very short
example.
This is for Larry I Smith:
class A1
{
public:
A1(int val) : m_x(val) {}
int x() const { return m_x; }

int add(const A1& oth)
{
m_x += oth.x();
This is unecessary. Different objects of the same class may access
their private and protected members directly.
return m_x;
}

private:
int m_x;
};

Here's another example using 'protected' data:
This example does not explain the use of protected data nor the
interaction between two objects using this features (such as a

derived class). I also do not understand why your first example uses a member function to access 'm_x' and the following one does not.
class A2
{
public:
A2(int val) : m_x(val) {}

int add(const A2& oth)
{
m_x += oth.m_x;
return m_x;
}

protected:
int m_x;
};

Jonathan


Jul 23 '05 #11
Jonathan Mcdougall wrote:
Larry I Smith wrote:


This is for Larry I Smith:
class A1
{
public:
A1(int val) : m_x(val) {}
int x() const { return m_x; }
int add(const A1& oth)
{
m_x += oth.x();
This is unecessary. Different objects of the same class may access
their private and protected members directly.
return m_x;
}
private:
int m_x;
};
Here's another example using 'protected' data:


This example does not explain the use of protected data nor the
interaction between two objects using this features (such as a derived
class). I also do not understand why your first example uses a member
function to access 'm_x' and the following one does not.


See my 2nd post (9 minutes after the original) - because I was
'brain-dead' and responded too quickly without thinking it through.
In my head I was thinking of derived classes, but I didn't
put that in my post.

Some days I shouldn't get out of bed...

Larry

--
Anti-spam address, change each 'X' to '.' to reply directly.
Jul 23 '05 #12
You are absolutely right. It works (today)! I must have been
'brain-dead' too, last night; I was getting some error, which probably
was irrelevant, and I thought that this was the problem (but I have a
tiny bit of an excuse: my class is quite big; I hadn't actually compiled
the simple one I sent to the newsgroup).

Anywayz. Thanks everybody for your replies.

Regards,
Manolis

PS: I didn't want to make it public or add functions to access/modify
the value, since only members of this class should know about (and thus
access/modify) the value.
Jonathan Mcdougall wrote:
I was wondering if there is any way to make two objects of the same
class to be able to access each other's private data, like this:


class A {
public:
void access( const A& a ) {cout<<"a.value="<<a.value<<endl; }
private:
int value;
};

This compiles fine:

#include <iostream>

class A
{
public:
void access( const A& a)
{
std::cout << "a.value=" << a.value << std::endl;
}

private:
int value;
};

It is legal for two A's to access their private members. What error do
you get?

Jonathan

Jul 23 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

49
by: Steven Bethard | last post by:
I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another...
6
by: Garma | last post by:
According to what I have learnt so far, instantiating global objects should be the last resort. Is there any reasons why so? Sometimes some objects or their pointers have to be shared among...
106
by: xtra | last post by:
Hi Folk I have about 1000 procedures in my project. Many, many of them are along the lines of function myfuntion () as boolean on error goto er '- Dim Dbs as dao.database Dim Rst as...
0
by: Nashat Wanly | last post by:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaskdr/html/askgui06032003.asp Don't Lock Type Objects! Why Lock(typeof(ClassName)) or SyncLock GetType(ClassName) Is Bad Rico...
14
by: tshad | last post by:
I have people telling me that I should set up objects for my tables, but I am finding the Null problem makes that difficult. It isn't a big problem if you are not updating the table, but if you...
4
by: lars.uffmann | last post by:
Hey everyone! I am (still) working on a project that I took over from former students, so don't blame me for the criminal approach on coding *g* The problem I have is fairly easy and while I...
31
by: attique63 | last post by:
how could I write a program that will declare a class point. The class point has two private data members x and y of type float. The class point has a parameterized constructor to initialize both...
1
by: Nemisis | last post by:
hi guys, Currently converting an old classic asp system to a OOP asp.net application. We are building the new application using a 3 tier arcitecture and i was wondering about the following. ...
6
by: Guy Thornton | last post by:
I have an application in asp.net using vb. The asp.net portion of this application is mainly the user interface. The UI has references made to our business logic layer. And the business logic...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.