BEST SITE FOR WEB DEVELOPERS

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Strings C++ Math C++ Booleans C++ Conditions C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Access Specifiers C++ Encapsulation C++ Inheritance C++ Polymorphism C++ Files C++ Exceptions C++ Date

C++ How To

Add Two Numbers Random Numbers

C++ Reference

C++ Reference C++ Keywords C++ <iostream> C++ <fstream> C++ <cmath> C++ <string> C++ <cstring> C++ <ctime>

C++ Examples

C++ Examples C++ Compiler C++ Exercises C++ Quiz C++ Certificate

C++ Language. W3Schools in English. Lessons for beginners

Ua Es De

C++ Encapsulation


Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public get and set methods.


Access Private Members

To access a private attribute, use public "get" and "set" methods:

Example

#include <iostream>
using namespace std;

class Employee {
  private:
    // Private attribute
    int salary;

  public:
    // Setter
    void setSalary(int s) {
      salary = s;
    }
    // Getter
    int getSalary() {
      return salary;
    }
};

int main() {
  Employee myObj;
  myObj.setSalary(50000);
  cout << myObj.getSalary();
  return 0;
}
Try it Yourself »

Example explained

The salary attribute is private, which have restricted access.

The public setSalary() method takes a parameter (s) and assigns it to the salary attribute (salary = s).

The public getSalary() method returns the value of the private salary attribute.

Inside main(), we create an object of the Employee class. Now we can use the setSalary() method to set the value of the private attribute to 50000. Then we call the getSalary() method on the object to return the value.


Why Encapsulation?

  • It is considered good practice to declare your class attributes as private (as often as you can). Encapsulation ensures better control of your data, because you (or others) can change one part of the code without affecting other parts
  • Increased security of data


Comments