Welcome back! We're now shifting our focus to another essential concept in Object-Oriented Programming (OOP): encapsulation. Encapsulation helps us bundle the data (variables) and methods (functions) that operate on the data into a single unit called a class
. It also helps restrict access to some of the object's components.
In this lesson, you will learn how to:
Let's look at the following C++ example to get a better understanding:
C++1#include <iostream> 2#include <string> 3 4// Person class with private data members name and age 5class Person { 6public: 7 Person(const std::string& name, int age) : name(name), age(age) {} 8 9 // Setters for setting the name and age 10 11 void setName(const std::string& name) { 12 this->name = name; 13 } 14 15 void setAge(int age) { 16 this->age = age; 17 } 18 19 // Getters for getting the name and age 20 21 std::string getName() const { 22 return name; 23 } 24 25 int getAge() const { 26 return age; 27 } 28 29private: 30 std::string name; 31 int age; 32}; 33 34int main() { 35 // Create a Person object and set the name and age 36 Person person("Alice", 30); 37 person.setName("Bob"); 38 person.setAge(25); 39 40 // Get the name and age of the person and print them 41 std::cout << "Name: " << person.getName() << ", Age: " << person.getAge() << std::endl; 42 43 return 0; 44}
In this example, we have a Person
class with private data members name
and age
. The class provides public methods (setName
, setAge
, getName
, and getAge
) for manipulating and accessing these private members.
If we skip setters and getters and make the data members public, we lose control over the data and can't enforce constraints or validations. Encapsulation allows us to protect the object's internal state and provide controlled access to it.
Encapsulation is fundamental in software development for several reasons:
class
maintains its own state and behavior, so changes in one class usually don't affect others.Understanding and applying encapsulation will make your code more secure, prevent bugs related to invalid states, and improve code clarity.
Ready to explore how encapsulation can make your code robust and secure? Let's head over to the practice section and implement these concepts together!