

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 void
and it will take a string attribute(string new Color;
) in order to use it as a value for the attribute color
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 string
and it will not take attributes/parameters.#include <iostream>
#include <string>
using namespace std;
class Car {
private:
string color;
string make;
string model;
public:
string getColor() {
return color;
}
void setColor(string newcolor) {
color = newcolor;
}
};
int main() {
Car newCar;
newCar.setColor("Red");
cout << "encapsulation example print color: " <<newCar.getColor() << "\n";
return 0;
}
Output
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.Conclusion
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: mockstacks@gmail.com.
Share On: |
Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.