C++ Class Access Specifiers: public

Introduction

Public access members are accessible anywhere.

For example, they are accessible to other class members and to objects of our class.

To access a class member from an object, we use the dot . operator.

Let's define a class where all the members have public access.

To define a class with public access specifier, we can write:

class MyClass 
{ 
public: 
    int x; 
    void printx() 
    { 
        std::cout << "The value of x is:" << x; 
    } 
}; 

Let us instantiate this class and use it in our main program:

#include <iostream> 

class MyClass // ww  w.  j a  v  a  2 s  .  c  om
{ 
public: 
    int x; 
    void printx() 
    { 
        std::cout << "The value of data member x is: " << x; 
    } 
}; 

int main() 
{ 
    MyClass o; 
    o.x = 123;    // x is accessible to object o 
    o.printx();   // printx() is accessible to object o 
} 

Our object o now has direct access to all member fields as they are all marked public.

Member fields always have access to each other regardless of the access specifier.

That is why the member function printx() can access the member field x and print or change its value.




PreviousNext

Related