{"id":80912,"date":"2021-06-10T09:00:01","date_gmt":"2021-06-10T03:30:01","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=80912"},"modified":"2021-06-10T09:00:01","modified_gmt":"2021-06-10T03:30:01","slug":"encapsulation-in-cpp","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/","title":{"rendered":"Encapsulation in C++"},"content":{"rendered":"<p>C++, being a versatile programming language, has got various Object-Oriented Programming features. Encapsulation is one of the important OOP features provided by C++, it enables the programmer to incorporate data members and methods\/functions into a single constituent. That single unit or constituent is class, and this entire process is known as encapsulation.<\/p>\n<p><strong>Let\u2019s take a real-life example: <\/strong><\/p>\n<p>In an IT company, a software engineer from a different team is working on a project that needs entry from the database. The engineer then needs to ask for permission from the database engineer to access data from the database, since there is a restriction in the data for the different team members. This is what encapsulation is.<\/p>\n<p>The data in the database is not visible for the software engineer as it is the data for another team that can manipulate everything that is wrapped under \u201cdatabase department\u201d.<\/p>\n<h3>Types of Encapsulation in C++<\/h3>\n<p>In C++ there are three different ways to implement encapsulation:<\/p>\n<p>1. Member variable encapsulation<br \/>\n2. Function encapsulation<br \/>\n3. Class encapsulation<\/p>\n<p>As the names clearly depict, in member variable encapsulation all the data variables or data members are declared private. Whereas, in Function Encapsulation, some of the functions and constructors are declared private. While in Class Encapsulation, the entire class is declared as private (usually done in the case of multiple classes).<\/p>\n<h3>C++ Data Encapsulation Examples<\/h3>\n<p>Example 1:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\nclass Sum {\n  public:\n    \/\/ Data Variables required for adding two numbers\n    int num1;\n    int num2;\n    \n    \/\/constructor to initialize the two numbers\n    Sum (int x, int y)\n    {\n        num1=x;\n        num2=y;\n    }\n\n    \/\/ Function to calculate sum\n    int get() {\n      return num1 + num2;\n    }\n};\n\nint main() {\n  \/\/ Create object of Sum class\n  Sum obj(6,9);\n\n  \/\/ Call get() function\n  cout &lt;&lt; \"Sum = \" &lt;&lt; obj.get();\n\n  return 0;\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\"><span style=\"font-weight: 400\">Sum = <\/span><span style=\"font-weight: 400\">15<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\">&#8230;Program finished with <\/span><span style=\"font-weight: 400\">exit<\/span><span style=\"font-weight: 400\"> code <\/span><span style=\"font-weight: 400\">0<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\">Press ENTER to <\/span><span style=\"font-weight: 400\">exit<\/span><span style=\"font-weight: 400\"> console.<\/span><\/div>\n<p>In this example, we needed two variables num1 and num2 along with functions get() and constructor to calculate the sum of two numbers. Hence, we combined all these data members and variables into a single Sum class.<\/p>\n<p><strong>Note<\/strong>: In the above example as we declared every data member and functions as public it is also accessible to the other classes. Therefore, this is not data hiding.<\/p>\n<p>Encapsulation refers to combining the related variables and functions together, which can be used to achieve data hiding. Hence, encapsulation is not always data hiding.<\/p>\n<p><strong>Example 2:<\/strong><\/p>\n<p>In Data Hiding, there is restricted access to the data members and functions. Usage of access specifiers helps us achieve data hiding. For example,<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">\/\/ Program to calculate the sum of two numbers\n#include &lt;iostream&gt;\nusing namespace std;\n\nclass Sum {\n  private:\n    \/\/ Data Variables required for adding two numbers\n    int num1;\n    int num2;\n    \/\/Function to set the two numbers\n\n  public:\n    void set(int x, int y)\n    {\n        num1=x;\n        num2=y;\n    }\n    \/\/ Function to calculate sum\n    int get() {\n      return num1 + num2;\n    }\n};\n\nint main() {\n  \/\/ Create object of Sum class\n  Sum obj ;\n  obj.set(6,9);\n  \/\/ Call get() function\n  cout &lt;&lt; \"Sum = \" &lt;&lt; obj.get();\n  return 0;\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\"><span style=\"font-weight: 400\">Sum = <\/span><span style=\"font-weight: 400\">15<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\">&#8230;Program finished with <\/span><span style=\"font-weight: 400\">exit<\/span><span style=\"font-weight: 400\"> code <\/span><span style=\"font-weight: 400\">0<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\">Press ENTER to <\/span><span style=\"font-weight: 400\">exit<\/span><span style=\"font-weight: 400\"> console.<\/span><\/div>\n<p>In the above example, we declared the data variables private and hence we could not access it from the main() method as it is outside the class. For that, we had to create a set() function and pass the values to the class members. Since the data is hidden, we can not simply use constructors to initialize the variables.<\/p>\n<h3>Role of Access Specifiers in C++<\/h3>\n<p>As seen from the above examples, in C++ we can use access specifiers or modifiers to implement encapsulation and further achieve data hiding which will help the programmers in many different ways.<\/p>\n<p>There are 3 types of access specifiers according to which one can implement encapsulation:<\/p>\n<h4>1. Public:<\/h4>\n<p>Member functions or methods can be declared as public so that they can manipulate the data members.<\/p>\n<h4>2. Private:<\/h4>\n<p>The data members should be declared as private so that they can not be accessed by members from different classes. By default, all members of the class are declared private.<\/p>\n<h4>3. Protected:<\/h4>\n<p>This access specifier is only used in case of inheritance, we will learn about this in a different tutorial.<\/p>\n<p><strong>Let\u2019s take an example:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class example {\n  public:       \n    int num1;   \/\/ Public data member\n  private:      \n    int num2;   \/\/ Private data member\n};\n\nint main() {\n  example obj;\n  obj.num1 = 5;  \/\/ Allowed \n  obj.num2 = 7;  \/\/ Will throw an error\n  return 0;\n}\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\"><span style=\"font-weight: 400\">main.cpp:<\/span><span style=\"font-weight: 400\">11<\/span><span style=\"font-weight: 400\">:<\/span><span style=\"font-weight: 400\">7<\/span><span style=\"font-weight: 400\">: error: <\/span><span style=\"font-weight: 400\">&#8216;int example::num2&#8217;<\/span><span style=\"font-weight: 400\"> is <\/span><span style=\"font-weight: 400\">private<\/span><span style=\"font-weight: 400\"> within <\/span><span style=\"font-weight: 400\">this<\/span><span style=\"font-weight: 400\"> context<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\"> \u00a0 obj.num2 = <\/span><span style=\"font-weight: 400\">7<\/span><span style=\"font-weight: 400\">;\u00a0 <\/span><span style=\"font-weight: 400\">\/\/ Will throw an error<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\"> \u00a0 \u00a0 \u00a0 ^~~~<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\">main.cpp:<\/span><span style=\"font-weight: 400\">5<\/span><span style=\"font-weight: 400\">:<\/span><span style=\"font-weight: 400\">9<\/span><span style=\"font-weight: 400\">: note: declared <\/span><span style=\"font-weight: 400\">private<\/span><span style=\"font-weight: 400\"> here<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\"> \u00a0 \u00a0 <\/span><span style=\"font-weight: 400\">int<\/span><span style=\"font-weight: 400\"> num2; \u00a0 <\/span><span style=\"font-weight: 400\">\/\/ Private data member<\/span><span style=\"font-weight: 400\"><br \/>\n<\/span><span style=\"font-weight: 400\"> \u00a0 \u00a0 \u00a0 \u00a0 ^~~~<\/span><\/div>\n<p>Clearly, we can now infer those data members declared as private are not accessible from the outside world. When we used an object to pass the value it threw an error, which shows that the main() method is restricted to access that private data member.<\/p>\n<h3>Benefits of C++ Encapsulation<\/h3>\n<p><span style=\"font-weight: 400\">1. In C++, encapsulation helps to combine the related members into a single class, making the code look cleaner and increasing readability.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">2. The get() and set() functions provide read-only and write-only accessibility to the user. Hence, keeping the data secure.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">3. The bundling of the data eases out the development in general. The testing, debugging, and execution of these bundles can be done individually, which will not affect the other parts.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">4. Data hiding is a good way to keep the data secure from the outside world. Hence, improving the security of the code even further.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">5. Encapsulation provides us with efficient control of the data as we can alter one part of the code without affecting the other.\u00a0<\/span><\/p>\n<h4>Designing Strategy<\/h4>\n<p><span style=\"font-weight: 400\">By learning encapsulation you will get a good habit of defining data members as private. This way we can keep our data secure from the outside world. This technique is mostly applied to member variables, but we can apply it to member functions as well. In this way, we can use encapsulation regularly.\u00a0<\/span><\/p>\n<h3>Difference between Data Abstraction and Encapsulation<\/h3>\n<table>\n<tbody>\n<tr>\n<td><b>Data Abstraction<\/b><\/td>\n<td><b>Encapsulation<\/b><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Data Abstraction solves the problems by proposing a design.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Encapsulation implements the proposed design and solves the problems.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">Data Abstraction hides the details of the code and only displays what the user needs.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Encapsulation helps in combining the data members including variables and functions into a single unit called class.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">In Abstraction, the use of classes and objects increases the security of the code.<\/span><\/td>\n<td><span style=\"font-weight: 400\">In Encapsulation, the use of access specifiers helps to restrict access to the data from the outside world.<\/span><\/td>\n<\/tr>\n<tr>\n<td><span style=\"font-weight: 400\">The hiding of the implementation is done in Abstraction.<\/span><\/td>\n<td><span style=\"font-weight: 400\">Using Encapsulation, the information can be kept hidden.\u00a0<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h3>Summary<\/h3>\n<p><span style=\"font-weight: 400\">In this article from TechVidvan, we talked about encapsulation and how it is helpful with a real-life example. We went further to discuss the examples of how one can implement encapsulation. <\/span><\/p>\n<p><span style=\"font-weight: 400\">Through those examples, we understood the concept of data hiding and how it is different from encapsulation. We also threw light upon the advantages of encapsulation and how it would be good to practice encapsulation in our codes.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">Keep Learning!<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>C++, being a versatile programming language, has got various Object-Oriented Programming features. Encapsulation is one of the important OOP features provided by C++, it enables the programmer to incorporate data members and methods\/functions into&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":80938,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3405],"tags":[3503,3504,1886,3505],"class_list":["post-80912","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cpp","tag-access-specifiers-in-c","tag-benefits-of-c-encapsulation","tag-data-abstraction-vs-encapsulation","tag-encapsulation-in-c"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Encapsulation in C++ - TechVidvan<\/title>\n<meta name=\"description\" content=\"Encapsulation is defined as wrapping up of data and information under a single unit. Learn more about Encapsulation in C++ with Examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Encapsulation in C++ - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Encapsulation is defined as wrapping up of data and information under a single unit. Learn more about Encapsulation in C++ with Examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-06-10T03:30:01+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Encapsulation-in-C.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Encapsulation in C++ - TechVidvan","description":"Encapsulation is defined as wrapping up of data and information under a single unit. Learn more about Encapsulation in C++ with Examples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/","og_locale":"en_US","og_type":"article","og_title":"Encapsulation in C++ - TechVidvan","og_description":"Encapsulation is defined as wrapping up of data and information under a single unit. Learn more about Encapsulation in C++ with Examples.","og_url":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-06-10T03:30:01+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Encapsulation-in-C.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Encapsulation in C++","datePublished":"2021-06-10T03:30:01+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/"},"wordCount":980,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Encapsulation-in-C.jpg","keywords":["Access Specifiers in C++","Benefits of C++ Encapsulation","Data Abstraction Vs Encapsulation","Encapsulation in C++"],"articleSection":["C++ Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/","url":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/","name":"Encapsulation in C++ - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Encapsulation-in-C.jpg","datePublished":"2021-06-10T03:30:01+00:00","description":"Encapsulation is defined as wrapping up of data and information under a single unit. Learn more about Encapsulation in C++ with Examples.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Encapsulation-in-C.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Encapsulation-in-C.jpg","width":1200,"height":628,"caption":"Encapsulation in C++"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/encapsulation-in-cpp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Encapsulation in C++"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/80912","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=80912"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/80912\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/80938"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=80912"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=80912"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=80912"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}