What is Public Access Specifier in C++


An access specifier is a defining code element that can determine which elements of a program are allowed to access a specific Member variable and member function. The Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.

The program defines a class named student, which has two public data members name and age, and a public member function display(). The class represents a student and its data.

In the main() function, an object of the student class is created using the default constructor. Then, the user is prompted to enter the student's name and age through standard input using cin. The entered values are stored in the object's name and age data members. Finally, the display() member function of the student class is called on the object to output the entered values to the standard output using cout.

The public access specifier allows the name and age data members to be accessed and modified from outside the student class, and also allows the display() member function to be called from outside the class to display the values of name and age. This means that any other function or object in the program can access and modify the name and age data members and call the display() member function on a student object.

Overall, this program provides an example of using a simple class definition in C++ with public access specifier to encapsulate and manipulate data related to a student object.

Source Code

#include<iostream>
using namespace std;
/*
Access Specifier
    Public
    Private
    Protected
*/
//What is Public Access Specifier in C++
class student
{
public:
    string name;
    int age;
 
    void display()
    {
        cout<<"Name :"<<name<<endl;
        cout<<"Age  :"<<age<<endl;
    }
};
int main()
{
    student o;
    cout<<"\nEnter Name & Age :"<<endl;
    cin>>o.name;
    cin>>o.age;
    o.display();
 
     return 0;
}
 

Output

Enter Name & Age :
Ram
23
Name :Ram
Age  :23
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples