How is the keyword “public” used in C++?
Understanding the Public Keyword in C++
In C++, the public
keyword is an access specifier that plays a crucial role in object-oriented programming. It defines the accessibility of class members (variables and functions) from outside the class. When a member is declared as public
, it can be accessed by any function that has access to an object of the class.
What is an Access Specifier?
C++ provides three access specifiers to control how class members can be accessed:
- public: Members are accessible from outside the class
- private: Members are only accessible within the class
- protected: Members are accessible within the class and by derived classes
Using the Public Keyword
The public
keyword is used within a class definition to declare a section where all members will have public access. Here’s the basic syntax:
class ClassName {
public:
// Public members go here
// Member variables
// Member functions
};
Public Member Variables
When a member variable is declared as public, it can be directly accessed and modified by any code that has access to the class object:
class Student {
public:
string name;
int age;
double gpa;
};
int main() {
Student student1;
// Direct access to public members
student1.name = "John Doe";
student1.age = 20;
student1.gpa = 3.8;
cout << "Name: " << student1.name << endl;
cout << "Age: " << student1.age << endl;
cout << "GPA: " << student1.gpa << endl;
return 0;
}
Public Member Functions
Public member functions (also called methods) define the interface of a class. They are the primary way for external code to interact with the class:
class BankAccount {
private:
double balance;
public:
// Constructor
BankAccount(double initialBalance) {
balance = initialBalance;
}
// Public member functions
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: $" << amount << endl;
}
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrew: $" << amount << endl;
} else {
cout << "Insufficient funds or invalid amount" << endl;
}
}
double getBalance() {
return balance;
}
};
Public Constructors and Destructors
Constructors and destructors are typically declared as public to allow objects to be created and destroyed:
class Car {
private:
string model;
int year;
public:
// Public constructor
Car(string m, int y) {
model = m;
year = y;
cout << "Car object created" << endl;
}
// Public destructor
~Car() {
cout << "Car object destroyed" << endl;
}
void displayInfo() {
cout << "Model: " << model << ", Year: " << year << endl;
}
};
Public Inheritance
When a class inherits from another class using public inheritance, public members of the base class remain public in the derived class:
class Vehicle {
public:
string brand;
void start() {
cout << "Vehicle started" << endl;
}
};
class Car : public Vehicle {
public:
string model;
void drive() {
cout << "Car is driving" << endl;
}
};
int main() {
Car myCar;
// Accessing public members from base class
myCar.brand = "Toyota";
myCar.start();
// Accessing public members from derived class
myCar.model = "Camry";
myCar.drive();
return 0;
}
Best Practices for Using Public Members
While public members provide easy access, it's important to follow best practices:
- Encapsulation Principle: Keep member variables private and provide public getter/setter functions to control access
- Interface Design: Make only necessary functions public to maintain a clean interface
- Data Validation: Use public functions to validate data before modifying private variables
- Consistency: Be consistent in your approach to accessibility across your codebase
Public vs. Private: A Comparison
Understanding when to use public versus private access is key to good object-oriented design:
class Employee {
private:
// Private members - internal implementation details
double salary;
string employeeId;
public:
// Public members - interface for external interaction
string name;
string department;
// Constructor
Employee(string n, string dept, double sal) {
name = n;
department = dept;
salary = sal;
employeeId = generateEmployeeId();
}
// Public function to access private data safely
double getSalary() {
return salary;
}
// Public function to modify private data with validation
void setSalary(double newSalary) {
if (newSalary > 0) {
salary = newSalary;
}
}
private:
// Private helper function
string generateEmployeeId() {
// Implementation details hidden from outside
return "EMP" + to_string(rand() % 10000);
}
};
Common Use Cases for Public Members
Public members are commonly used in these scenarios:
- Interface Functions: Functions that define how external code interacts with the class
- Constants: Public static constants that represent fixed values
- Utility Functions: Helper functions that don't depend on object state
- Getters and Setters: Functions that provide controlled access to private variables
Conclusion
The public
keyword in C++ is a fundamental concept in object-oriented programming that controls the accessibility of class members. By understanding how to use public members effectively, you can create well-designed classes that balance encapsulation with accessibility. Remember to follow best practices by keeping implementation details private and exposing only what's necessary through a clean public interface.