C++ public Keyword
The public keyword in C++ is an access specifier that determines the accessibility of class members. Members declared as public can be accessed from anywhere in the program, including outside the class. This makes public members directly accessible by objects of the class or by other classes and functions.
By default, all members of a struct are public, while all members of a class are private unless explicitly specified.
Syntax
</>
Copy
class ClassName {
public:
// Public members
};
- class
- The keyword used to define a class.
- public
- The access specifier indicating that the members below it are accessible from outside the class.
- members
- The data members or member functions that are accessible from anywhere in the program.
Examples
Example 1: Accessing Public Members
In this example, you will learn how public members of a class can be accessed directly using an object of the class.
</>
Copy
#include <iostream>
using namespace std;
class Person {
public:
string name; // Public data member
int age; // Public data member
void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Person person;
person.name = "Alice"; // Directly access public member
person.age = 30; // Directly access public member
person.display(); // Call public member function
return 0;
}
Output:
Name: Alice, Age: 30
Explanation:
- The
nameandagemembers are declared aspublic, allowing direct access from outside the class. - The
displaymethod, alsopublic, prints the values of the public members. - In the
mainfunction, an object of thePersonclass is used to assign and display the values of the public members.
Example 2: Public Members in a struct
In this example, you will learn how members of a struct are public by default.
</>
Copy
#include <iostream>
using namespace std;
struct Point {
int x; // Public by default
int y; // Public by default
void display() {
cout << "Point: (" << x << ", " << y << ")" << endl;
}
};
int main() {
Point p;
p.x = 5; // Directly access public member
p.y = 10; // Directly access public member
p.display(); // Call public method
return 0;
}
Output:
Point: (5, 10)
Explanation:
- The
Pointstructure has two data members,xandy, which arepublicby default. - The
displaymethod prints the values ofxandy. - In the
mainfunction, thexandymembers are accessed and modified directly, and the result is displayed using thedisplaymethod.
Key Points about public Keyword
- The
publickeyword allows members of a class to be accessed from anywhere in the program. - Members of a
structarepublicby default, whereas members of aclassareprivateby default. - Use
publicmembers for operations that need to be accessible outside the class, such as interface methods or direct data manipulation (though the latter is discouraged for encapsulation). - Public members are the most accessible but should be used carefully to maintain encapsulation and data integrity.
