Why do C++ classes have access specifiers ?

Thread Starter

skyr6546

Joined Mar 22, 2019
55
I'm new to C++, . The first thing I was wondering about when I started looking at C++ code is that classes have access specifiers such private, protected and public.

Code:
#include <iostream>
using namespace std;

class MyClass {
  public:    // Public access specifier
    int x;
  private:   // Private access specifier
    int y;  
protected;   // Protected access specifier
    int z;
};

int main() {
   
  MyClass myObject;

   myObject.x = 25;  // (x is public)
   myObject.y = 50;  // (y is private)
   myObject.z = 30; //  (z is protected)
 
  return 0;
}
Compilation failed due to following error(s).

error: 'int MyClass::y' is private within this context
myObject.y = 50; // Not allowed (y is private)
^
sky.cpp:8:9: note: declared private here
int y;
^
sky.cpp:19:13: error: 'int MyClass::z' is protected within this context
myObject.z = 30; //
^
sky.cpp:10:9: note: declared protected here
int z;
^
I was just wondering, what exactly is the purpose of declaring private, protected and public.
 

BobTPH

Joined Jun 5, 2013
2,047
The access specifiers are used to limit which code can access the members. If you create a class type that has internal variables that you do not want to user of the class to see, you make them private. Then only the methods of the class can access these members. And therefore the class implementation can rely on the fact that these members are not changed outside of the class members.

Bob
 

WBahn

Joined Mar 31, 2012
24,849
Also, by making elements private you insulate the users from the implementation details. The person writing/maintaining the class needs to take care to keep the behavior of public items consistent because people can access them and have possibly written code that relies on how they currently behave. But since they can't access the private items, the maintainer has the ability to radically change how the internals of the class work without risking breaking code that uses the class.
 

Thread Starter

skyr6546

Joined Mar 22, 2019
55
Also, by making elements private you insulate the users from the implementation details. The person writing/maintaining the class needs to take care to keep the behavior of public items consistent because people can access them and have possibly written code that relies on how they currently behave. But since they can't access the private items, the maintainer has the ability to radically change how the internals of the class work without risking breaking code that uses the class.
Okay What's the benefits of making private item in the following code

Code:
#include <iostream>
using namespace std;
 
#define MAX 10
 
class student
{
    private:
        char  name[30];
        int   rollNo;
        int   total;
        float perc;
        
    public:
        //member function to get student's details
        void getDetails(void);
        //member function to print student's details
        void putDetails(void);
};
 
//member function definition, outside of the class
void student::getDetails(void){
    cout << "Enter name: " ;
    cin >> name;
    cout << "Enter roll number: ";
    cin >> rollNo;
    cout << "Enter total marks outof 500: ";
    cin >> total;
    
    perc=(float)total/500*100;
}
 
//member function definition, outside of the class
void student::putDetails(void){
    cout << "Student details:\n";
    cout << "Name:"<< name << ",Roll Number:" << rollNo << ",Total:" << total << ",Percentage:" << perc;
}
 
int main()
{
    student std[MAX];       //array of objects creation
    int n,loop;
    
    cout << "Enter total number of students: ";
    cin >> n;
    
    for(loop=0;loop< n; loop++){
        cout << "Enter details of student " << loop+1 << ":\n";
        std[loop].getDetails();
    }
    
    cout << endl;
    
    for(loop=0;loop< n; loop++){
        cout << "Details of student " << (loop+1) << ":\n";
        std[loop].putDetails();
    }
    
    return 0;
}
Enter name: ian
Enter roll number: 12
Enter Branch: CS
name: ian
roll number: 12
Branch: CS
 

philbowles2012

Joined Mar 28, 2013
42
Data that is fundamental to the function of the class and/or which has validity constraints should not be accessible to the user. If it is he/she can modify it easily (and /or unwittingly) and thus break your class with a single line of code.

Also, I wouldn't use this particular instance as an example...it has many style / functionality issues...BUT since its here: perc is a good example. As written(!) perc can only be a valid percentage. If it were public, I could put any old rubbish into which is likely to break any subsequent code that assumes it will be a value between zero and 100.

std[n].perc=666; // disaster

If they can't see it, they can't mess with it. Google "data hiding" or read the link I posted above.
 

WBahn

Joined Mar 31, 2012
24,849
Okay What's the benefits of making private item in the following code
To a large degree, exactly what I said. What if you decide you want to change how you store the name from a fixed-length string to a dynamically allocated one? If you make the variable public then users can write code that accesses it in ways you can't control and hence changing how you represent it can mess up their code. Also, notice that this class is not doing proper input validation -- the user can enter a string that is too long. You should do that validation within your input method. But if the string is publicly accessible, no amount of input validation will prevent the user from accessing it directly and putting in a string that is too long and overflowing the array bounds.
 
Top