Encapsulation in C++ Last Updated : 15 May, 2025 Summarize Comments Improve Suggest changes Share Like Article Like Report Encapsulation is defined as the wrapping up of data and information in a single unit. In Object Oriented Programming, encapsulation is defined as binding together the data and the functions that manipulate them.Consider a real-life example of encapsulation, in a company, there are different sections like the accounts section, finance section, sales section, etc. Now,The finance section handles all the financial transactions and keeps records of all the data related to finance. All the financial processes are done by this section.Similarly, the sales section handles all the sales-related activities and keeps records of all the sales.This is what Encapsulation is. Encapsulation in C++In C++, OOPs encapsulation is implemented using classes and access specifiers that keeps the data, and the manipulating methods enclosed inside a single unit. The direct advantage of this packaging is that only the required components are visible to the user, and other information is hidden.Example C++ class Person { public: // Data/information int socialID; string name; // Functions that work in this data Person(string n, int id) {} bool validateID() {} }; In the above, encapsulation is demonstrated through the Person class, which encapsulates both data and the methods that represents the details of a real-world person.Encapsulation facilitates data hiding in C++ by using private, protected and public access specifiers for restricting access to the class member functions and data members. For example, the above class Person can be rewritten as: C++ class Person { // Data/information not accessible outside int socialID; string name; public: // Functions that work in this data Person(string n, int id) {} bool validateID() {} }; The class has two private data members: socialID and name. The private access specifier ensures that the socialID and name cannot be accessed directly from outside the class, enforcing data hiding. But there may be cases where you need to access or modify the private members such as name. This can be done by using getter and setter methods: C++ #include <iostream> using namespace std; // Class that represents a person class Person { // private members that will be hidden int socialID; string name; public: // public members that are accessible Person(string n, int id) { name = n; socialID = id; } string getName() { return name; } bool validateID() { if (socialID <= 1001 && socialID >= 0) return true; else return false; } }; int main() { Person p1("Shubham", 503); if (!p1.validateID()) cout << "Invalid SocialID\n"; cout << p1.getName(); return 0; } OutputAbhishekPublic method getName() provide controlled access to the name data. Similar function to modify the name can also be created.Note: The general encapsulation can be implemented using techniques other than classes but in OOPs language, it is implemented using classes.AdvantagesBelow are some main advantages of encapsulation:Modularity: Encapsulation promotes modularity by organizing code into separate objects that handle specific tasks, making the program more structured and easier to manage.Code Maintenance: Encapsulation helps in maintaining and updating the code more easily.Improved Security: By hiding data and restricting unauthorized access to it, encapsulation improves the security of the program.Decoupling: It helps in reducing the dependency between components of a system, allowing them to function independently and making the system easier to maintain and extend.Facilitates Implementation of Other OOP Features: It also makes it possible to implement other OOPs features such as polymorphism, inheritance, abstraction, etc.Encapsulation and AbstractionEncapsulation also leads to abstraction. Abstraction can be viewed as showing only the important information and ignoring the unimportant details and its internal working. In a class, public members functions are provided to the user without telling him/her about how it is implemented. That data remains hidden.While both contribute to good OOP design, there are differences between encapsulation and abstraction:Encapsulation is fundamentally about bundling data with the methods that operate on it to control access and prevent unintended modifications. Abstraction, on the other hand, is about interface design and simplification, presenting a high-level view while hiding complex implementation details.Encapsulation is also different from data hiding. It is the technique that facilitates data hiding using access specifiers in OOPs language, but not the data hiding itself. Comment More infoAdvertise with us Next Article Abstraction in C++ H Harsh Agarwal Improve Article Tags : C++ CPP-OOPs Practice Tags : CPP Similar Reads C++ Tutorial | Learn C++ Programming C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why 5 min read Introduction to c++Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m 3 min read Setting up C++ Development EnvironmentC++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro 8 min read Header Files in C++C++ offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the ".h" extension unlike in C, Where all the header files must necessarily end with the ".h" extension. Header files in C++ are basically used to declare an in 6 min read Namespace in C++Name conflicts in C++ happen when different parts of a program use the same name for variables, functions, or classes, causing confusion for the compiler. To avoid this, C++ introduce namespace.Namespace is a feature that provides a way to group related identifiers such as variables, functions, and 6 min read Writing First C++ Program - Hello World ExampleThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu 4 min read BasicsC++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ 7 min read C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable 4 min read Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu 9 min read Basic Input / Output in C++In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes 5 min read Control flow statements in ProgrammingControl flow refers to the order in which statements within a program execute. While programs typically follow a sequential flow from top to bottom, there are scenarios where we need more flexibility. This article provides a clear understanding about everything you need to know about Control Flow St 15+ min read C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int 7 min read Functions in C++A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the 9 min read C++ ArraysIn C++, an array is a derived data type that is used to store multiple values of similar data types in a contiguous memory location.Arrays in C++Create an ArrayIn C++, we can create/declare an array by simply specifying the data type first and then the name of the array with its size inside [] squar 10 min read Strings in C++In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class.Creating a StringBefore using s 5 min read Core ConceptsPointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a 5 min read new and delete Operators in C++ For Dynamic MemoryIn C++, when a variable is declared, the compiler automatically reserves memory for it based on its data type. This memory is allocated in the program's stack memory at compilation of the program. Once allocated, it cannot be deleted or changed in size. However, C++ offers manual low-level memory ma 6 min read Templates in C++C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so 9 min read Structures, Unions and Enumerations in C++Structures, unions and enumerations (enums) are 3 user defined data types in C++. User defined data types allow us to create a data type specifically tailored for a particular purpose. It is generally created from the built-in or derived data types. Let's take a look at each of them one by one.Struc 3 min read Exception Handling in C++In C++, exceptions are unexpected problems or errors that occur while a program is running. For example, in a program that divides two numbers, dividing a number by 0 is an exception as it may lead to undefined errors.The process of dealing with exceptions is known as exception handling. It allows p 11 min read File Handling through C++ ClassesIn C++, programs run in the computerâs RAM (Random Access Memory), in which the data used by a program only exists while the program is running. Once the program terminates, all the data is automatically deleted. File handling allows us to manipulate files in the secondary memory of the computer (li 8 min read Multithreading in C++Multithreading is a technique where a program is divided into smaller units of execution called threads. Each thread runs independently but shares resources like memory, allowing tasks to be performed simultaneously. This helps improve performance by utilizing multiple CPU cores efficiently. Multith 5 min read C++ OOPSInheritance in C++The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio 10 min read C++ PolymorphismThe word polymorphism means having many forms. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So, the same person exhibits different behaviour in different situations. This is ca 5 min read Encapsulation in C++Encapsulation is defined as the wrapping up of data and information in a single unit. In Object Oriented Programming, encapsulation is defined as binding together the data and the functions that manipulate them.Consider a real-life example of encapsulation, in a company, there are different sections 4 min read Abstraction in C++Data abstraction is one of the most essential and important features of object-oriented programming in C++. Abstraction means displaying only essential information and ignoring the details. Data abstraction refers to providing only essential information about the data to the outside world, ignoring 4 min read Standard Template Library (STL)Containers in C++ STLStandard Template Library (STL) provides the built-in implementation of commonly used data structures known as containers. A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the data type 3 min read Iterators in C++ STLAn iterator in C++ is a pointer-like object that points to an element of the STL container. They are generally used to loop through the contents of the STL container in C++. The main advantage of STL iterators is that they make the STL algorithms independent of the type of container used. We can jus 10 min read C++ STL Algorithm LibraryStandard Template Library (STL) offers a rich collection of algorithms designed to operate on STL containers and beyond. It provides commonly used algorithms such as sorting, searching, copying, etc. These well tested algorithms are optimized for performance and provide a way to write cleaner, faste 3 min read Practice ProblemC++ Interview Questions and Answers (2025)C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i 15+ min read C++ Programming ExamplesWriting C++ programs yourself is the best way to learn the C++ language. C++ programs are also asked in the interviews. This article covers the top practice problems for basic C++ programs on topics like control flow, patterns, and functions to complex ones like pointers, arrays, and strings.Basic C 7 min read Like