How to have a class have access the another class' private members?

littletemple

Golden Member
Sep 18, 2001
1,359
0
0
if I have a class called Test and another called Test2, how can have access to Test2's private members in the class Test? I read somewhere that you declared Test2 as a friend class of Test1 but I don't remember the syntax. If anyone knows and help, i would appreciate it.

 

Bloodstein

Senior member
Nov 8, 2002
343
0
0
Hmn...I'm assuming java here....

If Test and Test2 are part of the same PACKAGE and if you didn't explicitly use "private" on the class vars of Test2, then you can refer to Test2's vars by simply using the dot notation. However, the best (and most good programmers would agree with me here) way to access Test2's private vars is by creating public accessor methods to them...

I have never heard of declaring a class to be friendly....

Actually, could you be talking of superclass/subclass relationships?
If Test is a subclass of Test2, then you could probably use the dot notation to access the vars...again provided that the vars are not explicitly marked "private"

Hope that helps
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
in Test2:

public int getPrivate(){
return privateInt;
}

in Test:
int variable = testTwoObject.getPrivate();
 

TheDiggler

Senior member
Dec 23, 2002
695
0
0
This sounds like a C++ question.

class Test
{
// Insert public, protected, and/or pirvate class Test definitions
}

class Test2
{
friend class Test;
// Test is now a "friend" of Test2, so Test has access to EVERYTHING in Test2
// Insert public, protected, and/or private class Test2 definitions here
}

*EDIT* A simple Yahoo/Google search on "C++ friend syntax" will find you plenty of additional resources.
 

Bloodstein

Senior member
Nov 8, 2002
343
0
0
Originally posted by: TheDiggler
This sounds like a C++ question.

class Test
{
// Insert public, protected, and/or pirvate class Test definitions
}

class Test2
{
friend class Test;
// Test is now a "friend" of Test2, so Test has access to EVERYTHING in Test2
// Insert public, protected, and/or private class Test2 definitions here
}

*EDIT* A simple Yahoo/Google search on "C++ friend syntax" will find you plenty of additional resources.

Hmn...interesting...

This actually kills the idea of class hierarchy. Would this affect polymorphism?

 

TheDiggler

Senior member
Dec 23, 2002
695
0
0
Originally posted by: Bloodstein

Hmn...interesting...

This actually kills the idea of class hierarchy. Would this affect polymorphism?

Not really, although I don't recall the precise rules of inheritence when a BASE CLASS has a "friend" defined but a CHILD CLASS doesn't. I'm fairly sure ALL virtual methods of the BASE CLASS re-defined in the CHILD CLASS are accessible to the "friend" CLASS. I'm not sure though whether any newly defined protected & private methods of the CHILD CLASS are accessible to the "friend" CLASS (assuming the "friend" is only declared in the BASE CLASS).

Originally posted by: Nothinman
If you're gonna do that, you might as well just declare all of them public.

Disagreed. The moment you declare something public, it's open game to ANYONE/ANYTHING (all classes, external functions, etc). The C++ "friend" clause lets you allow SPECIFIC CLASSES to have open access to a particular class, not EVERYTHING.

P.S. No need to shoot me, I'm only a messenger! :p I'm not remotely talented enough to write a language, let alone C++ :Q
 

Nothinman

Elite Member
Sep 14, 2001
30,672
0
0
Disagreed. The moment you declare something public, it's open game to ANYONE/ANYTHING (all classes, external functions, etc). The C++ "friend" clause lets you allow SPECIFIC CLASSES to have open access to a particular class, not EVERYTHING.

I realize the difference, but it seems to me that if you start declaring classes as friends you're avoiding they key reason to mark things private in the first place.I would think it would be better design to either incorporate the 'friend's functionality in the other class, hell they're dependent on each other now anyway, or make the data public (or atleast have a public setup/set function) because you've obviously found a reaon to want to update it from outside that class.
 

Armitage

Banned
Feb 23, 2001
8,086
0
0
Originally posted by: Nothinman
Disagreed. The moment you declare something public, it's open game to ANYONE/ANYTHING (all classes, external functions, etc). The C++ "friend" clause lets you allow SPECIFIC CLASSES to have open access to a particular class, not EVERYTHING.

I realize the difference, but it seems to me that if you start declaring classes as friends you're avoiding they key reason to mark things private in the first place.I would think it would be better design to either incorporate the 'friend's functionality in the other class, hell they're dependent on each other now anyway, or make the data public (or atleast have a public setup/set function) because you've obviously found a reaon to want to update it from outside that class.

There are plenty of legitimate reasons for friend classes & functions. The classic example for friend functions is overloading the '<<' and '>>' operators for IO.

The case for friend classes is a little tougher, but it still exists. I'll look at it in terms of your counter arguments...

incorporate the 'friend's functionality in the other class

A class should always be an 'is a' type of object. ie. it should represent a distinct & narrowly defined entity. To combine two classes because they need to interact would muddy this considerably.

make the data public (or atleast have a public setup/set function) because you've obviously found a reaon to want to update it from outside that class.

A friend class or function does not necesarily update or change data in the classes it has friend relationshiop(s) with, but in any case, there are legitimate reasons not to make the data, or access functions needed public. For example, one place I use friend is in my vector & matrix classes. Look at the example of matrix - vector multiplication.

Array A(3, 3); // a 3x3 array
Vector x(3), y(3); //vectors of size 3

//...initialization...

x = A*y;

Now, I could certainly implement this via the public api ... the overloaded '[]' and '()' operators. But those operators on the array side have to calculate row offsets, on the array & vector side they could have range checking turned on, etc. Using the pyublic API would be VERY slow compared to an algorithm that does pointer math directly on the raw internal representation for both objects. And of course, making that raw internal representation public would be a big mistake.

Here's what the public data access functions look like for example:
class Vector
{
public:
virtual double &operator[](int c)
{
#ifdef DEBUG
check_index(c);
#endif
return pt[c - 1]; //API index starts @ 1, internal representation starts @ 0
}
}

class Array
{
public:
virtual double &operator()(int r, int c)
{
#ifdef DEBUG
check_index(r, c);
#endif
return pt[(r - 1)*columns + c - 1];
}
}

Here is the implementation of the Array- Vector multiplication

Vector Array:: operator*(const Vector &x) const
{
#ifdef DEBUG
if(x.size() != columns)
array_error("ERROR: Incompatible Array & Vector sizes in call to Array:: operator*(Vector)", 2);
#endif

Vector T(rows);

int i, j;
T.zero();

double *rPT = T.pt; //pointer to the start of the result Vector representation
double *xPT; //pointer to the start of the x Vector representation
double *PT = pt; //pointer to the start of the Array representation

for(i=1; i<=rows; i++)
{
xPT = x.pt;
for(j=1; j<=columns; j++)
{
*rPT += *(PT++) * *(xPT++);
}
rPT++;
}

return T;
}

I can assure you that this is significantly faster then using the public api (overloaded '[]' and '()' operators)

Another case in which I use class friends is my satellite, ground point and sensor classes. The sensor class has legitimate reasons to need direct access to the internal representations of the satellite & ground point classes. A sensor object can be attached to either of these. But the internal representations of these classes should not be publicly exposed because manipulations of them have other repercussions within the class that could'nt be easily handled.
 

Descartes

Lifer
Oct 10, 1999
13,968
2
0
Meiler Page-Jones would say this constituted coalescing classes increasing connassence of class, but lets not get too verbose.

Protected fields make it all too easy for subclasses to break encapsulation (i.e. coalescing classes). I'm against protected fields in almost all cases. Protected methods is an entirely different issue.
 

manly

Lifer
Jan 25, 2000
12,767
3,564
136
Nobody is saying friends are without purpose. What Nothinman is saying, and I mostly agree, is use an appropriate accessor method when simple data encapsulation is the goal. Exposing a specific, focused API publicly is almost certainly better than opening up a class completely to a friend.