Access Specifiers

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Access Specifiers

Access specifiers specifies the access rights of the data members and member functions of
class

In general programming language has 3 types of access specifiers

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 C++ the default access specifier is private

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.

public private protected


Same Program Class Y Y Y
Same Program Subclass Y N Y
Same Program Non Subclass Y N Y
Different Program Subclass Y N Y
Different Program Non Subclass Y N N

Here's an example of how access specifiers in a C++ program

#include <iostream>

// Define a class called 'Person'


class Person {
public:
// Public access specifier
// Public members are accessible from anywhere
std::string name;

// Public member function


void introduce() {
std::cout << "Hello, I am " << name << std::endl;
}

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) {}

// Public member function to access the age


int getAge() {
return age;
}

// Public member function to set the age


void setAge(int newAge) {
age = newAge;
}
};

int main() {
// Create an instance of the 'Person' class
Person person("Alice", 30, 5.6);

// Access public members


person.introduce();

// Access and modify protected member (age)


int currentAge = person.getAge();
std::cout << "Current age: " << currentAge << std::endl;
person.setAge(31);
std::cout << "New age: " << person.getAge() << std::endl;

// Private members are not accessible from outside the class


// person.height = 6.0; // This would result in a compilation error

return 0;
}

You might also like