C++ Encapsulation

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this C++ tutorial, let us have a look at C++ Encapsulation, its syntax and sample C++ program for a better understanding of this concept.

Introduction to Encapsulation in C++

In general, Encapsulation is the pillar of Object-Oriented Programming that focuses on the security/safety of data by hiding it to secure from unauthorized access.

Data encapsulation in C++ is a mechanism of wrapping the data and the function that manipulates them under a single unit. 

Properties of Encapsulation

C++ supports the properties of encapsulation through the creation of user-defined types, called classes, and it contains private, protected and public members.

class Road {
      double getVolume(void) {
         return length * breadth * height;
      double length; // Length of a road
      double breadth; // Breadth of a road
      double height; // Height of a road

The variable’s length, breadth, and height are private. This means that they can be accessed only by members of the Road class, and not by any other members of the program. In this way, the encapsulation concept is achieved.

Program for C++ Encapsulation

#include <iostream>
using namespace std;
class Adder {
      // constructor
      Adder(int i = 0) {
         total = i;
      // interface to outside world
      void addNum(int number) {
         total += number;
      // interface to outside world
      int getTotal() {
         return total;
      // hidden data from outside world
      int total;
int main() {
   Adder a;   
   cout << "Total " << a.getTotal() <<endl;
   return 0;


Total 60

Leave a Comment

Your email address will not be published. Required fields are marked *