Hey was just wondering if there was a way I could share the private data with another class, without including it as a object of that class, for example, i have 2 classes, class A and blass B. class 'A' reads in from a txt file and stores its data in 2 string arrays, such as string firstname[100]; string lastname[100]; which are in the private section, how would i copy this into class B?

what i want to do is basically strcpy(classB.firstname, classA.firstname);

is this possible?

thanx for your reply, Ive been looking around and havent been able to get it to work with a friends class :S is there any other way of doing it? i might be doing it wrong lol

> You could maybe try creating pointers in the public section of your class and point them to the private data you want to share ...

But you should definitely learn how to use a 'friend', it's a much better way to do this ...

> You could also create an extra class which holds all the data which has to be shared among the other classes ...

It seems it depends which order you declare the classes matters? For example, this does not compile:

class Point
{
	private:
		//friend class PointFriend;
		double x,y,z;

	public:
		Point(const double xin, const double yin, const double zin) : x(xin), y(yin), z(zin) {}
};

class PointFriend
{
	private:
		friend class Point;
	public:
		PointFriend()
		{
			Point P(1.2, 2.3, 3.4);
			cout << P.x << endl;
		}
};

But if you uncomment the "friend class PointFriend;" and comment "friend class Point", it works correctly.

Why is that?

Dave

For example, this does not compile:

class Point
{
	private:
		//friend class PointFriend;
		double x,y,z;

	public:
		Point(const double xin, const double yin, const double zin) : x(xin), y(yin), z(zin) {}
};

class PointFriend
{
	private:
		friend class Point;
	public:
		PointFriend()
		{
			Point P(1.2, 2.3, 3.4);
			cout << P.x << endl;
		}
};

But if you uncomment the "friend class PointFriend;" and comment "friend class Point", it works correctly.

PointFriend must be a friend of Point because PointFriend's constructor accesses a private member of Point (i.e. P.x).

Whether or not "friend class Point;" is declared in the above example makes no difference because class Point does not make any use of class PointFriend. If it would, then you'd have to split the code into .h and .cpp files with appropriate #includes in order to have a mutual friendship.

P.S. Note that you can also have individual member functions as friends of a class.

Ah, I though I had read somewhere that the friendship was mutual - ie. if you make A a friend of B, then B is automatically a friend of A, but I guess that is just wrong, as this example shows haha.

Thanks,

Dave

This article has been dead for over six months. Start a new discussion instead.