0
0
C++programming~5 mins

Access specifiers in C++

Choose your learning style9 modes available
Introduction

Access specifiers control who can see and use parts of your code. They help keep things safe and organized.

When you want to hide details inside a class so others can't change them by mistake.
When you want to allow some parts of your program to use certain data but keep others away.
When you want to protect important information inside your code from being changed directly.
When you want to organize your code clearly by showing which parts are for inside use and which are for outside use.
Syntax
C++
class ClassName {
public:
  // accessible from anywhere
protected:
  // accessible in this class and derived classes
private:
  // accessible only in this class
};

public: means anyone can use these parts.

protected: means only this class and its children can use these parts.

private: means only this class can use these parts.

Examples
Here, length is public, so anyone can access it.
C++
class Box {
public:
  int length;
};
Here, width is private, so only Box can use it.
C++
class Box {
private:
  int width;
};
Here, height is protected, so Box and its children can use it.
C++
class Box {
protected:
  int height;
};
Sample Program

This program shows how speed is private and cannot be changed directly. Instead, we use public functions to set and show the speed.

C++
#include <iostream>
using namespace std;

class Car {
private:
  int speed;

public:
  void setSpeed(int s) {
    speed = s;
  }
  void showSpeed() {
    cout << "Speed: " << speed << " km/h" << endl;
  }
};

int main() {
  Car myCar;
  // myCar.speed = 100; // Error: speed is private
  myCar.setSpeed(100);
  myCar.showSpeed();
  return 0;
}
OutputSuccess
Important Notes

Private members cannot be accessed outside the class directly.

Protected members are useful when you want child classes to access some data but keep it hidden from others.

Public members are open to everyone, so use them carefully.

Summary

Access specifiers control who can use parts of a class.

Use private to hide details inside a class.

Use public to allow outside access.

Use protected to allow access in child classes.