Friday, 5 April 2019

Access Specifiers / Modifiers in C++

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class).

Access modifiers or Access Specifiers in a class are used to set the accessibility of the class members. That is, it sets some restrictions on the class members not to get directly accessed by the outside functions.

Moving ahead to type of access specifiers, they are:

Public - The members declared as Public are accessible from outside the Class through an object of the class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

int main()
{
    MyClass obj;
    obj.a = 10;     //Allowed
    obj.b = 20;     //Not Allowed, gives compiler error
    obj.c = 30;     //Not Allowed, gives compiler error
}



Inheritance and Access Specifiers

Inheritance in C++ can be one of the following types:
    1. Private Inheritance
    2. Public Inheritance
    3. Protected inheritance
      Source:
      1. stackoverflow.com
      2.www.geeksforgeeks.org

      0 comments:

      Post a Comment

      Advertisement

      Find Us On Facebook

      C Programming

      More

      C++ Tutorial

      More

      Java Tutorial

      More

      Computer Basics

      More

      MS Office

      More

      Database Management

      More
      Top