Access Specifiers
Access Specifiers
Access specifiers specifies the access rights of the data members and member functions of
class
public : members declared public can be accessed from anywhere in the program and also
from outside the program.
private : members declared private can be accessed within the class in which it is defined.
Members cannot be accessed from outside that class.
protected : members declared protected acts same as the private access specifier, the only
difference is that protected members are inheritable whereas private members are not.
In Java the default access specifier is package-private which specifies that the
member with no access specifier can be accessed from anywhere within the
package it is declared in but cannot be accessed from outside the package.
#include <iostream>
protected:
// Protected access specifier
// Protected members are accessible within this class and its subclasses
int age;
private:
// Private access specifier
// Private members are only accessible within this class
double height;
public:
// Constructor to initialize the name, age, and height
Person(const std::string& n, int a, double h) : name(n), age(a), height(h) {}
int main() {
// Create an instance of the 'Person' class
Person person("Alice", 30, 5.6);
return 0;
}