0% found this document useful (0 votes)
10 views

Example Program

The document explains encapsulation in C++ with an example program. The program uses private and public access specifiers to make a variable accessible only through getter and setter methods, binding the variable and methods together. Abstraction in C++ is also explained with an example using private variables that can only be accessed and manipulated through public methods.

Uploaded by

sd501250
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Example Program

The document explains encapsulation in C++ with an example program. The program uses private and public access specifiers to make a variable accessible only through getter and setter methods, binding the variable and methods together. Abstraction in C++ is also explained with an example using private variables that can only be accessed and manipulated through public methods.

Uploaded by

sd501250
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

4. C++ encapsulation program.

// c++ program to explain


// Encapsulation

#include<iostream>
using namespace std;
class Encapsulation
{
private:
// data hidden from outside world
int x;

public:
// function to set value of
// variable x
void set(int a)
{
x =a;
}
// function to return value of
// variable x
int get()
{
return x;
}
};
// main function
int main()
{
Encapsulation obj;
obj.set(5);
cout<<obj.get();
return 0;
}

Explanation of program: In the above program the variable x is made private. This variable can be
accessed and manipulated only using the functions get() and set() which are present inside the class.
Thus we can say that here, the variable x and the functions get() and set() are bonded together which is
nothing but encapsulation.
5. C++abstraction program.

#include <iostream>
using namespace std;
class implementAbstraction
{
private:
int a, b;

public:
// method to set values of
// private members
void set(int x, int y)
{
a = x;
b = y;
}
void display()
{
cout<<"A = " <<a << endl;
cout<<"B = " << b << endl;
}
};
int main()
{
implementAbstraction obj;
obj.set(10, 20);
obj.display();
return 0;
}

Explanation of program: You can see in the above program we are not allowed to access the variables a
and b directly, however one can call the function set() to set the values in a and b and the function
display() to display the values of a and b.

You might also like