CPP access modifier public, private and protected

 Access modifiers

There are three types of access modifiers in CPP: private, protected, and public. These modifiers are commonly used in classes. These modifiers change the visibility  of class members from outside the class block.

Public 

All public members of a class can be accessed from anywhere in the program.

Private 

All private members of a class can not be accessed from out of the scope of
that class only methods and friend functions present in that class can access
them.

Protected

A class's private and protected members cannot be accessed from outside the class scope, however, unlike the private, the protected member can be inherited by the subclass (child class).

Example code 

class MyClass {

private:

// All private members 

// Comes under the private keword followed by a : at the end.

// The same applies to other modifiers.

const char* data;

Int size;

public:

void print(){

  std::cout << data << std::endl;

}

void write(const char* data){

   This -> data = data;

    size = strlen(data);

}

protected: 

// This class does not have any protected members.

}

Int main() {

  MyClass obj;

  obj.write("this member is accesible here");

  obj.data; // since the data is private to this class, we cant access it here

  obj.size; // not accesible

  obj.print(); // accessible because it's a public member as write()

return 0;

}

Share this Post

Leave a Reply

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