C++ Encapsulation
Encapsulation is the concept in object-oriented programming (OOP) where data members (attributes) and functions (methods) are bundled together inside a class. This ensures that data is protected and controlled via specific methods.
In encapsulation, it is indeed common and standard practice to make
- data members (variables) Private
- and the functions (methods) public.
This approach is a key aspect of encapsulation in object-oriented programming (OOP), and it helps in achieving data hiding and controlled access to the data.
Simple Encapsulation Example in C++
#include <iostream> using namespace std;class Person { private: // Private data members string name; int age; public: // Getter method to get the name // Setter method to set the age // Getter method to get the age int main() { // Set the name and age using setter methods // Get and display the name and age using getter methods return 0; |
Explanation:
-
Private Data Members:
name
andage
are private variables. They cannot be accessed directly from outside thePerson
class.
-
Public Methods:
- Setter methods (
setName
,setAge
) allow you to set values forname
andage
. - Getter methods (
getName
,getAge
) allow you to retrieve the values ofname
andage
.
- Setter methods (
-
Main Function:
- A
Person
objectp
is created. - The
setName
andsetAge
methods are used to set thename
andage
. - The
getName
andgetAge
methods are used to display the values ofname
andage
.
- A
Output:
Name: John
Age: 25