The word “encapsulate” has two meanings: to express yourself succinctly, and to enclose something in a protective way. We can similarly use encapsulation in C++ to do these very things through the use of classes.
This article explains encapsulation and how we can use setters and getters in C++ to read and modify protected data. We’ll cover two examples, with one showing how you can use these tools to protect and streamline your program. The other introduces getters and setters and how they allow us to access private data.
What Is Encapsulation?
In C++, encapsulation involves combining similar data and functions into a single unit called a class. By encapsulating these functions and data, we protect that data from change. This concept is also known as data or information hiding.
Let’s look at an example of C++ class encapsulation:
...
class Passport {
string country_of_origin;
int passport_number;
string passport_name;
void dothis() {
cout << passport_name << "'s " << country_of_origin << " passport number is " << passport_number;
}
};...
Within the class Passport, we declared the variables and methods that we wanted to include. Note that we can only use cout() if we wrap it in a function, as classes can execute member functions but not objects.
What Are the Advantages of Encapsulation in C++?
Keeping pertinent code encapsulated within a class helps streamline your program. You can contain your code in one location so your code is easier to follow.
This, in turn, makes your program easier to debug. If a function within your encapsulated class is not working correctly, you’ll likely be able to pinpoint the problem to the class instead of having to comb through your code.
When you encapsulate, you can control the flow of data into and out of a class. Classes allow you to make certain functions or variables inaccessible to protect them from being used or changed outside of the class. You can also make specific components accessible to use elsewhere in your code.
Let’s look at the tools that allow you to protect or enable access to a class’s variables or functions.
C++ Class Access Modifiers
When adding data members or functions to a class, we can use one of three keywords to control their access:
Private: We can only use any class member or function listed as private within the class they belong to. Trying to access or view private data outside of their respective class results in an error.
Protected: Protected members or functions are limited in their use as well. In addition to using protected members or functions within their class, we can also access protected information from within inherited classes.
Public: We can use public members and functions anywhere else in our code.
While we don’t cover inherited classes that use the protected keyword here, below is an example of how public and private access modifiers work:
...class Passport {
private:
string country_of_origin;
public:
int passport_number;
string passport_name;
void dothis() {
cout << passport_name << "'s " << country_of_origin << " passport number is " << passport_number;
}
};...
Building on our example, we declare country_of_origin as a private string. This means we cannot view or access this string from outside of our Passport class.
However, we have made both passport_number and passport_name public so we can interact with those two variables outside of our class. We’ll look at how to do this in just a bit.
If you don’t assign an access modifier to your data members or functions inside your class, C++ will assume those data members and functions are private.
Printing From an Encapsulated Class in C++
The above example is a valid class, but it has some limitations. We are free to use or assign values to passport_number and passport_name in an instance of the Passport class anywhere else in our code. This also leaves these variables exposed, allowing other parts of the codebase to manipulate them in a way we had not intended.
However, the country_of_origin string is private and therefore inaccessible by the rest of our program. We can assign country_of_origin a value as we declare it, but this means we cannot change it elsewhere:
...class Passport {
private:
string country_of_origin = "United States";
public:
int passport_number;
string passport_name;
void dothis() {
cout << passport_name << "'s " << country_of_origin << " passport number is " << passport_number;
}
};
int main() {
Passport mypassport;
mypassport.passport_number = 476896564;
mypassport.passport_name = "Reginald Higginbom";
mypassport.dothis();
return 0;
}
The above program runs and outputs the information in the cout statement:
Reginald Higginbom's United States passport number is 476896564
Had we not assigned a value to country_of_origin within the Passport class and tried to do so in main, we would have received the following error:
main.cpp:19:13: error: 'std::string Passport::country_of_origin' is private within this context
mypassport.country_of_origin = "United States";
^~~~~~~~~~~~~~~~~
Fortunately, there’s a way to read or modify data from within the private area of a class in main.
How To Access Private Encapsulated Data in C++
C++ allows access to private data members and functions inside a class through the use of getters and setters. get() and set() are methods, initialized in the public section of a class, as a way to either read or write to private data.
set() enables us to write a value to a private variable within our class. get(), on the other hand, allows a function outside of the class to read private data. Using set() and get() allows us to protect data members or functions in our class while still being able to use them.
Ideally, we want to make our passport information private to prevent other users from tampering with it. With setters and getters in C++, we can still modify that data. The example below shows how set and get functions look in code:
...void setpassport_number(int passnum) {
passport_number = passnum;
}
int getpassport_number() {
return passport_number;
}...
We create a function called setpassport_number() with one parameter that permits us to write a value to passport_number, a private variable. Similarly, we introduce getpassport_number() to read that value outside of our class.
Our completed class has three private variables and all the setters and getters we need to read and write to those variables. Note that setters and getters need to be public so that we can use them outside of our class. Our Passport class looks like this:
...class Passport {
int passport_number;
string passport_name;
string country_of_origin;
public:
void setPassport_number(int passnum) {
passport_number = passnum;
} void setPassport_name(string passname) {
passport_name = passname;
}
void setCountry_of_origin(string origin) {
country_of_origin = origin;
}
int getPassport_number() {
return passport_number;
}
string getPassport_name() {
return passport_name;
}
string getCountry_of_origin() {
return country_of_origin;
}
};
...
Lastly, we add a main() function to execute our new class, assign values to our private variables, and output the result:
int main() {
Passport mypassport;
mypassport.setpassport_number(476896564);
mypassport.setpassport_name("Reginald Higgins");
mypassport.setcountry_of_origin("United States");
cout << mypassport.getpassport_name() << "'s " << mypassport.getcountry_of_origin() << " passport number is " << mypassport.getpassport_number();
return 0;
}
We can call on the set() and get() functions we created in main() because we listed them as public in our class. If we run the program in its entirety, it outputs:
Reginald Higgins's United States passport number is 476896564
We arrive at the same result as our earlier example, but our class is encapsulated from outside interference.
Learn Programming With Udacity
C++ is one of a handful of programming languages that incorporates classes. You can use classes to encapsulate data members and functions, both protecting your code and making it easier to read. Setters and getters allow manipulation of private code from outside the class.
Ready to become a C++ developer?
If you’re completely new to programming, start with our Introduction to Programming nanodegree.
But if you already have some experience and want to dive right into C++, enroll in our C++ nanodegree instead.
Complete Code Examples
Example 1: Encapsulating data members and functions
#include <iostream>
using namespace std;
class Passport {
private:
string country_of_origin = "United States";
public:
int passport_number;
string passport_name;
void dothis() {
cout << passport_name << "'s " << country_of_origin << " passport number is " << passport_number;
}
};
int main() {
Passport mypassport;
mypassport.passport_number = 476896564;
mypassport.passport_name = "Reginald Higgins";
mypassport.dothis();
return 0;
}
Example 2: Getters and setters in action
#include <iostream>
using namespace std;
class Passport {
int passport_number;
string passport_name;
string country_of_origin;
public:
void setPassport_number(int passnum) {
passport_number = passnum;
}
void setPassport_name(string passname) {
passport_name = passname;
}
void setCountry_of_origin(string origin) {
country_of_origin = origin;
}
int getPassport_number() {
return passport_number;
}
string getPassport_name() {
return passport_name;
}
string getCountry_of_origin() {
return country_of_origin;
}
};
int main() {
Passport mypassport;
mypassport.setPassport_number(476896564);
mypassport.setPassport_name("Reginald Higgins");
mypassport.setCountry_of_origin("United States");
cout << mypassport.getPassport_name() << "'s " << mypassport.getCountry_of_origin() << " passport number is " << mypassport.getPassport_number();
return 0;
}



