C++ Encapsulation"Encapsulation" comes from "capsule". It means putting things together, closing them in a package, and the "things" we are talking about here are data and functions. Programming without encapsulation means that functions dealing with data are "floating around", somewhere in your code, and though they deal with your data and even take that particular type as input, they are separated from your data.
C++ example of encapsulation
In below example you can see that color attribute now defined as private so no direct access to attribute can be made. Also we created 2 new functions.
First function will set the value for color and it's called:
setColor()this function does not have a return value so return type is set as
voidand it will take a string attribute(
string new Color;) in order to use it as a value for the attribute
Second function will get the value of color and it's called:
getColor()this function does have a return value so return type is set as
stringand it will not take attributes/parameters.
encapsulation example print color: Red
Why Encapsulation?It is considered good practice to declare your class attributes as private. Encapsulation ensures better control of your data, because developers can change one part of the code without affecting other parts. it will also increase data security.
In this page (written and validated by A. Gawali) you learned about C++ Encapsulation . What's Next? If you are interested in completing Cpp tutorial, your next topic will be learning about: Cpp Inheritance.
Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: firstname.lastname@example.org.