In C++, access specifiers control the visibility and accessibility of class members (variables and functions). The public
access specifier allows class members to be accessed from outside the class.
1️⃣ Syntax of public
Access Specifier
class ClassName {
public:
// Public members (accessible from anywhere)
int data;
void display() {
cout << "Data: " << data << endl;
}
};
2️⃣ Example: Public Members in a Class
#include <iostream>
using namespace std;
class Car {
public:
string brand;
int year;
void showInfo() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
Car car1;
car1.brand = "Toyota"; // Public member accessible
car1.year = 2022;
car1.showInfo(); // Public function called
return 0;
}
Output:
Brand: Toyota, Year: 2022
Explanation:
brand
andyear
are declared aspublic
, so they can be accessed directly frommain()
.- The function
showInfo()
is alsopublic
, so it can be called outside the class.
3️⃣ Key Characteristics of public
Access Specifier
Feature | Description |
---|---|
Visibility | Public members can be accessed from anywhere. |
Direct Access | Variables and functions can be accessed directly. |
Inheritance Effect | When inherited, public members remain public in the derived class (unless changed). |
4️⃣ Public Access in Inheritance
When a class is inherited using public
mode, the public
members remain public
in the child class.
Example: Public Inheritance
#include <iostream>
using namespace std;
class Parent {
public:
void showMessage() {
cout << "This is a public function from Parent class." << endl;
}
};
class Child : public Parent { // Public Inheritance
};
int main() {
Child obj;
obj.showMessage(); // Accessible because it's public
return 0;
}
Output:
This is a public function from Parent class.
5️⃣ When to Use public
Access Specifier?
✅ When you need direct access to class members.
✅ When defining interface functions that should be accessible to users.
✅ When implementing class inheritance where functions should remain accessible in derived classes.
6️⃣ Comparison of Access Specifiers
Access Specifier | Accessible Inside Class | Accessible Outside Class | Accessible in Derived Class |
---|---|---|---|
public | ✅ Yes | ✅ Yes | ✅ Yes |
private | ✅ Yes | ❌ No | ❌ No |
protected | ✅ Yes | ❌ No | ✅ Yes |
Would you like to see examples with private and protected access specifiers next? 🚀
0 Comments