Access Specifiers in C++

A very important feature of C++ is Data Hiding.  Some of the data elements must be used within only a single class and must not be available to other classes or functions. Sometimes a data element is needed to be shared by two classes and unavailable for the rest.
To handle such situations, C++ has three Access Specifiers. These limit the scope of the variables/functions as per the requirements of the programmer.

These are:

  1. public
  2. private
  3. protected

1.       public: Making a data element public means allowing the access to that data type anywhere in the program(by using “.”operator outside the class). A public data element can be edited anywhere in the program.

          Syntax- public:

example- public:

int var1;

2.       private: Making a data element private means limiting the access to that data type within the class in which it is declared and defined. the member functions of that class can use that element even outside the class but no other function or class can access that data element.

          Syntax- private:

example- private:

int var2;

3.       protected: A data element declared as protected can be accessed by the member functions of the class and those of the class which is immediately derived from it. No other class can access the protected data elements.

          Syntax- protected:

example- protected:

int var3;

kaliadevansh has written 15 articles

2 thoughts on “Access Specifiers in C++

  1. games says:

    Hey outstanding blog! Does running a blog like this require a lot of work?
    I have very little understanding of programming however
    I was hoping to start my own blog in the near future.
    Anyways, should you have any suggestions or tips for new blog owners please share.
    I understand this is off subject however I just needed to ask.
    Thanks!

Cancel reply

Leave a Reply to k

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>