All Courses
OOP: ACCESS SPECIFIERS

`public` Access Specifier

public means a member can be accessed from outside the class.

Public members form the object's interface.

Public Interface

The public interface is what users of the class are allowed to call.

account.deposit(500);
account.withdraw(200);
account.displayBalance();

These are safe actions if the class validates them properly.

Example

#include <iostream>

class Circle {
private:
    double radius = 1.0;

public:
    void setRadius(double value) {
        if (value > 0) {
            radius = value;
        }
    }

    double area() const {
        return 3.14159 * radius * radius;
    }
};

int main() {
    Circle circle;
    circle.setRadius(5.0);
    std::cout << circle.area() << '\n';
}

Public Data Warning

Public data is allowed in C++, but it is often dangerous in OOP.

Bad:

class Circle {
public:
    double radius;
};

Then outside code can do:

circle.radius = -10;

That creates invalid state.

What Should Usually Be Public?

Usually public:

  • constructors
  • safe methods
  • getters
  • validated setters
  • behavior the outside world should use

Usually not public:

  • raw internal data
  • helper functions used only inside the class
  • implementation details

Viva Answer

public members can be accessed from outside the class. Public methods form the class interface, while data members are usually kept private so the class can protect its state.

Quick Check

  • What does public mean?
  • What is a public interface?
  • Why is public data risky?
  • Should constructors usually be public?