C++: Access controls

This entry is part 36 of 61 in the series C++

Throughout our earlier programs, we have declared the data members and data member functions as public.  Any program that uses an object of the class can access the public data members directly.

For the data members, we usually would set a restriction so that only members of the public functions can access them.

Consider the following example.

#include <iostream>
#include <string>

using namespace std;

class Rock

	string name = "Rod Stewart";
	string track = "I was only joking";


	int Display();


int Rock::Display()

	cout << "This is " << name << " Singing " << track;
	cout << endl;

	return 0;

int main()

	Rock rockstar; // instance declaration


	return 0;

We have the name and track declared as private in the class declaration.

This set a restriction such that only the public member functions can access it.

And in our example above, only the Display function can access the data members name and track.


Series Navigation<< C++: The this keyword
C++: Using Netbeans IDE >>

Leave a comment

Leave a Reply