In this code example, we explore data abstraction by utilizing public, private, and protected access specifiers within a Test
class. This example highlights how these access levels control the visibility and accessibility of class members. The Test
class contains three methods: privPrint
(private), protPrint
(protected), and pubPrint
(public), each demonstrating their respective accessibilities.
In the main
function, attempts to call privPrint
and protPrint
result in compilation errors, illustrating their restricted access, while pubPrint
is successfully called, showcasing its public accessibility. This example effectively demonstrates the principles of data abstraction in C++.
#include <iostream>
using namespace std;
class Test {
private:
void privPrint() {
cout << "I'm private" << endl;
}
public:
void pubPrint() {
cout << "I'm public" << endl;
}
protected:
void protPrint() {
cout << "I'm protected" << endl;
}
};
int main() {
Test t1;
// error: 'privPrint' is a private member of 'Test'
// t1.privPrint();
// error: 'protPrint' is a protected member of 'Test'
// t1.protPrint();
// works
t1.pubPrint();
return 0;
}
class Test {
The Test
class is declared, encapsulating its member functions within different access specifiers.
private:
void privPrint() {
cout << "I'm private" << endl;
}
The privPrint
function is declared under the private
access specifier, making it accessible only within the Test
class itself. It prints the message “I’m private” to the console.
public:
void pubPrint() {
cout << "I'm public" << endl;
}
The pubPrint
function is declared under the public
access specifier, making it accessible from outside the class. It prints the message “I’m public” to the console.
protected:
void protPrint() {
cout << "I'm protected" << endl;
}
The protPrint
function is declared under the protected
access specifier, making it accessible only within the Test
class and its derived classes. It prints the message “I’m protected” to the console.
int main() {
Test t1;
// error: 'privPrint' is a private member of 'Test'
// t1.privPrint();
The commented-out line attempts to call privPrint()
, which would result in a compilation error because privPrint
is private and inaccessible outside the Test
class.
// error: 'protPrint' is a protected member of 'Test'
// t1.protPrint();
The commented-out line attempts to call protPrint()
, which would also result in a compilation error because protPrint
is protected and inaccessible outside the Test
class.
// works
t1.pubPrint();
The pubPrint
function is called successfully, printing “I’m public” to the console because it is public and accessible from outside the class.
This C++ code demonstrates how access specifiers control the visibility of class members. It highlights that:
The output of the code will be:
I'm public
This output confirms that only the public member function pubPrint
is accessible from outside the Test
class, successfully printing its message to the console.