What are access specifiers in C++?
In this chapter of C++ interview questions, we will learn about:
-
what are access specifiers in c++
-
types of access specifiers in c++
-
examples of access specifiers in c++
Use of access specifiers in C++
Data Hiding is an important aspect of Object-Oriented Programming.
In C++ access specifiers are used to facilitate this feature. Access specifiers are used to provide certain level of permission to access data in class members.
Types of Access Specifiers
i) Private: Private members of a class are accessible only from within other members of the same class or from 'friends'.
ii) Protected: It is some similarity with a private access specifier. The difference it can be accessed from a derived class or friend class/ child class.
iii) Public: Public members are accessible from anywhere, it is accessed through access operator(.) with the object of the class.
Examples of access specifiers in c++(Public & Private)
class TIH {
public: // Public access specifier
int a;
private: // Private access specifier
int b;
};
int main() {
TIH obj; //Object created
obj.a = 22; // Allowed (public) accessed through (.) opeartor
obj.b = 43; // Not allowed (private)
return 0;
}
Output
error obj.b=43 // Not allowed
Examples of access specifiers in c++ (Protected)
#include <iostream>
using namespace std;
class A {
protected:
int x;
};
class B:A { // B is the derived class.
public:
void setting( int x1 );
int getting( void );
};
// Member functions of child class
int B::getting(void) {
return x ;
}
void B::setting( int x1) {
x = x1;
}
int main() {
B b1;
b1.setting(10);
cout << "Value is : "<< b1.getting() << endl;
return 0;
}
Output
Value is : 10
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Page Views :
Published Date :
Jan 19,2021