Differences between private, protected and public and give examples.



Differences between private, protected and public and give examples...

Answer / Abhishek Pathak

In C++, access specifiers are used to control the accessibility of a class member. The three main access specifiers are:n
1. Private (private): Members declared as private can only be accessed within their own class.nExample: `class Example {n private:n int x;n};`n
2. Protected (protected): Members declared as protected can be accessed by the members of their own class, derived classes, and friends of the class.nExample: `class Base {n protected:n int y;n};nclass Derived : public Base {n void print() {n cout << y;n }n};`n
3. Public (public): Members declared as public can be accessed by any function that has the object of the class.nExample: `class Example {n public:n int z;n};nvoid main() {n Example obj;n cout << obj.z;n}`nnThe key differences are in the accessibility level, with private having the lowest and public having the highest level of accessibility.

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More C++ General Interview Questions

how to create window program in c++.please explain.

1 Answers   Microsoft,


What is the difference between new() and malloc()?

5 Answers  


What is an ABC: an "Abstract Base Class"?

1 Answers  


how to explain our contribution in the project?

1 Answers   Wipro, Yahoo,


Why c++ is the best language?

1 Answers  


Explain deep copy and a shallow copy?

1 Answers  


Which one between if-else and switch is more efficient?

1 Answers  


In int main(int argc, char *argv[]) what is argv[0] a) The first argument passed into the program b) The program name c) You can't define main like that

1 Answers  


What is the array and initializing arrays in c++?

1 Answers  


List the types of polymorphism in c++?

1 Answers  


What is stream and its types in c++?

1 Answers  


Is c++ vector a linked list?

1 Answers  


Categories