December 3, 2022

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:

  1. 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
  1. create a file person.cpp
  2. include person.h
  3. 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
  1. create a main.cpp file
  2. include person.h file
#include "person.h"

int main(int argc, char const *argv[])
{
    Person p("ANOOP");
    std::cout << "Name : " << p.getName();
    return 0;
}
  1. Compilation
g++ main.cpp person.cpp
  1. 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;
}
Follow me

I work on everything coding and share developer memes