Abstraction & Encapsulation
Posted on December 3, 2022 • 2 minutes • 217 words
1. Abstraction
Data Abstraction involves presenting only the essential details to the outside world, i.e., representing only the essential details inside the program, and hiding the other details.
How to achieve Abstraction
1. By Header files.
Example:
- Create a header file
person.h
// person.h
#ifndef ANOOP_TUBE_PERSON_H
#define ANOOP_TUBE_PERSON_H
#include<iostream>
class Person
{
public:
Person(std::string name_);
std::string getName();
void setName(std::string name_);
private:
std::string name;
};
#endif
- create a file person.cpp
- include
person.h
- define all functions.
// person.cpp
#ifndef ANOOP_TUBE_PERSON_H
#define ANOOP_TUBE_PERSON_H
#include<iostream>
#include "person.h"
Person::Person(std::string name_)
{
name = name_;
}
std::string Person::getName()
{
return name;
}
void Person::setName(std::string name_)
{
name = name_;
}
#endif
- create a
main.cpp
file - include
person.h
file
#include "person.h"
int main(int argc, char const *argv[])
{
Person p("ANOOP");
std::cout << "Name : " << p.getName();
return 0;
}
- Compilation
g++ main.cpp person.cpp
- Run your binary
./a.out
2. By Classes and Access Specifiers.
Hiding unwanted data by using private or protected access specifiers.
Example:
// main.cpp
#include<iostream>
class Person
{
public:
Person(std::string name_)
{
name = name_;
}
std::string getName()
{
return name;
}
void setName(std::string name_)
{
name = name_;
}
// hide from out side of the class
private:
std::string name;
};
int main(int argc, char const *argv[])
{
Person p("ANOOP");
std::cout << "Name : " << p.getName();
return 0;
}