Encapsulation is a cornerstone principle of object-oriented programming (OOP) in C++. It revolves around bundling data (attributes) and the functions (methods) that operate on that data into a single unit called a class. This concept fosters several benefits:
By declaring data members as private within a class, you control access and prevent external code from modifying the data directly. This safeguards your program’s integrity and promotes better maintainability.
Classes encapsulate functionality, making code more organized and reusable. You can create self-contained units that represent real-world entities or concepts.
When data and its manipulation logic reside together, changes become more localized and less likely to introduce unintended side effects in other parts of your code.
Data hiding can restrict unauthorized access, protecting sensitive information within your program
A class is a blueprint that defines the properties (data members) and behaviors (member functions) of objects. It serves as a template for creating instances (objects) that embody these characteristics.
#include
#include
class Car {
private:
std::string model;
int year;
public:
// Constructor to initialize data members
Car(const std::string& model, int year) : model(model), year(year) {}
// Getter method to access the model (read-only)
std::string getModel() const { return model; }
// Setter method to modify the year (write-only)
void setYear(int newYear) { year = newYear; }
// Method to display car information
void displayDetails() const {
std::cout << "Model: " << model << std::endl;
std::cout << "Year: " << year << std::endl;
}
};
int main() {
// Create an instance of Car
Car myCar("Toyota Camry", 2020);
// Display car details
std::cout << "Before modification:" << std::endl;
myCar.displayDetails();
// Modify the year using setter method
myCar.setYear(2022);
// Display modified details
std::cout << "\nAfter modification:" << std::endl;
myCar.displayDetails();
return 0;
}
// output //
Before modification:
Model: Toyota Camry
Year: 2020
After modification:
Model: Toyota Camry
Year: 2022
Class Definition: We define a class Car
which encapsulates the data related to a car, including its model and year of manufacture.
Private Data Members: The model
and year
data members are marked as private
, meaning they can only be accessed within the class.
Constructor: The class has a constructor Car(const std::string& model, int year)
to initialize the model
and year
data members when a Car
object is created.
Getter Method: The getModel()
method is a getter function that allows read-only access to the model
member variable. It returns a std::string
containing the model.
Setter Method: The setYear(int newYear)
method is a setter function that allows modification of the year
member variable. It takes an integer parameter newYear
and updates the year
data member accordingly.
Display Method: The displayDetails()
method displays the car’s model and year on the console using std::cout
. It is marked as const
to indicate that it does not modify the object’s state.
Main Function: In the main()
function, we create an instance of the Car
class named myCar
with model “Toyota Camry” and year 2020.
Access and Modification: We first display the details of myCar
using the displayDetails()
method. Then, we modify the year of the car to 2022 using the setYear()
method.
Output: The program outputs the car details before and after modification.
C++ provides access specifiers to define the accessibility of class members:
Member functions operate on the data members of their class, providing a controlled way to interact with the object’s internal state. The const
keyword can be used with member functions to indicate that they don’t modify the object’s state.
Constructors: Special member functions that are automatically called when an object is created. They typically initialize the object’s data members.
Destructors: Special member functions that are automatically called when an object goes out of scope or is explicitly deleted. They can perform necessary cleanup tasks (e.g., deallocating memory).
Getters (Accessors): Public member functions that provide read-only access to private data members.
Setters (Mutators): Public member functions that allow controlled modification of private data members.
#include
class Account {
private:
double balance;
public:
// Constructor
Account(double initialBalance) : balance(initialBalance) {}
// Getter for balance
double getBalance() const { return balance; }
// Setter for balance (with validation)
void setBalance(double amount) {
if (amount >= 0) {
balance = amount;
} else {
std::cerr << "Error: Invalid balance." << std::endl;
}
}
};
int main() {
// Create an instance of Account
Account myAccount(1000.0);
// Display initial balance
std::cout << "Initial Balance: $" << myAccount.getBalance() << std::endl;
// Update balance
myAccount.setBalance(1500.0);
// Display updated balance
std::cout << "Updated Balance: $" << myAccount.getBalance() << std::endl;
// Attempt to set negative balance
myAccount.setBalance(-500.0);
return 0;
}
// output //
Initial Balance: $1000
Updated Balance: $1500
Error: Invalid balance.
Class Definition: We define a class Account
which encapsulates the data related to an account, specifically the balance.
Private Data Member: The balance
data member is marked as private
, meaning it can only be accessed within the class.
Constructor: The class has a constructor Account(double initialBalance)
to initialize the balance
when an Account
object is created.
Getter Method: The getBalance()
method is a getter function that allows read-only access to the balance
member variable. It returns a double
containing the balance.
Setter Method: The setBalance(double amount)
method is a setter function that allows modification of the balance
member variable. It takes a double
parameter amount
and updates the balance
data member accordingly. It also performs validation to ensure that the balance cannot be set to a negative value.
Main Function: In the main()
function, we create an instance of the Account
class named myAccount
with an initial balance of $1000.0.
Display Initial Balance: We display the initial balance of the account using the getBalance()
method.
Update Balance: We update the balance of the account to $1500.0 using the setBalance()
method.
Display Updated Balance: We display the updated balance of the account.
Invalid Balance: We attempt to set a negative balance (-$500.0), triggering the validation in the setBalance()
method. An error message is displayed to indicate the invalid balance.
int
, double
, char
, etc. can be used as data members.std::unique_ptr
, std::shared_ptr
) within member functions or constructors to manage memory automatically and prevent memory leaks.Encapsulation is a fundamental pillar of object-oriented programming in C++. It empowers you to create well-organized, maintainable, and secure code by bundling data and its manipulation logic within classes. By effectively using access specifiers, member functions, and advanced techniques like inheritance and polymorphism, you can build robust and scalable C++ applications.Happy coding !❤️