Introduction to Programming and C++

Contents Previous Topic Next Topic

Access to member variables, member functions, and static variables is defined by declaring these members to be one of private, protected, or public. This classification is universal: either a member variable or function is available to all external functions, only to member functions of derived classes, or to no external functions.

In some cases, it is necessary to allow access to private members to some external functions or perhaps even to entire external classes. The following class allows friendship to three external objects.

#include <iostream>
using namespace std;

class OpenBox;
void f( int );

class Box {
	private:
		int n;
	public:
		Box( int nn ):n(nn) {
			// empty constructor
		}

		friend class OpenBox;
		friend void f( int );
};

class OpenBox {
	private:
		Box a;
	public:
		OpenBox( int m ):a(m) {
			// empty constructor
		}

		void b() {
			cout << a.n << endl;
		}
};

void f( int m ) {
	Box box(m);

	cout << box.n << endl;
}

int main() {
	f(5);

	OpenBox open( 7 );
	open.b();

	return 0;
}

No other function is allowed to access the member variables of Box.

One slight variation on the above example is where the object stored is a pointer to an object:

#include <iostream>
using namespace std;

class OpenBox;
int f( int );

class Box {
	private:
		int n;
	public:
		Box( int nn ):n(nn) {
			// empty constructor
		}

		friend class OpenBox;
		friend int f( int );
};

class OpenBox {
	private:
		Box *ptr;
	public:
		OpenBox( int m ):ptr(new Box(m)) {
			// empty constructor
		}

		~OpenBox() {
			delete ptr;
		}

		int b() {
			cout << ptr->n << endl;
		}
};

int main() {
	OpenBox open( 7 );

	open.b();

	return 0;
}

Contents Previous Topic Top Next Topic