C++ Encapsulation
Published Oct 10, 2021Updated Dec 21, 2022
Contribute to Docs
Encapsulation is a way of organizing data members (attributes) and function members (methods) by wrapping them together in a single class. By bundling them together in a single unit, the code is cleaner, more readable, and more maintainable.
class Example {
// Some attributes
// Some methods
}
Here’s a Rectangle class with length and width attributes and a .Area() method:
class Rectangle {public:int length;int width;int Area() {return length * width;}};
Data Hiding
Encapsulation led to the important OOP concept of data hiding or abstraction.
Access specifiers are C++ keywords that determine the scope of class components:
public: Public class members are accessible from anywhere in the program.private: Private class members are only accessible from inside the class.
Data hiding is achieved by declaring class attributes as private:
#include <iostream>class Encapsulation {private:// Data hidden from outside worldint num;public:// Function to set value of numvoid setNum(int x) {num = x;}// Function to return value of numint getNum() {return num;}};int main() {Encapsulation obj;obj.setNum(10);std::cout << obj.getNum() << "\n"; // Output: 10return 0;}
In the example above, the num attribute and .setNum() and .getNum() methods are wrapped together into one class called Encapsulation.
numcan only be accessed by either the.setNum()or.getNum()method..setNum()is used to set the value ofnum..getNum()is used to return the value ofnum.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours