c-plus-plus
  1. c-plus-plus-data-abstraction

C++ Abstraction: Data Abstraction

Data abstraction is a programming technique that hides the underlying implementation details while only exposing the necessary information to the outside world. It is used to simplify complex programs by breaking down large objects into smaller, more manageable chunks.

Syntax

class MyClass {
private:
    int myVar;
public:
    void setMyVar(int var);
    int getMyVar();
};

Example

Let's create a class Person with private attributes name and age and public methods setName, setAge, getName and getAge that allow us to set and get these attributes:

class Person {
private:
    string name;
    int age;
public:
    void setName(string name);
    void setAge(int age);
    string getName();
    int getAge();
};

void Person::setName(string name) {
    this->name = name;
}

void Person::setAge(int age) {
    this-> age = age;
}

string Person::getName() {
    return name;
}

int Person::getAge() {
    return age;
}

int main() {
    Person p;
    p.setName("John");
    p.setAge(30);
    cout << "Name: " << p.getName() << endl;
    cout << "Age: " << p.getAge() << endl;
    return 0;
}

Output

Name: John
Age: 30

Explanation

In the example above, we have created a class Person with private attributes name and age and public methods setName, setAge, getName and getAge. These methods allow us to set and get the attributes of a Person object without directly accessing them. This is an example of data abstraction because we are abstracting away the implementation details of the Person class and only exposing the necessary information to the outside world.

Use

Data abstraction is useful for creating modular and scalable code. It allows us to break down complex programs into smaller, more manageable chunks that can be worked on independently. It also helps to prevent unwanted changes to the data by hiding the implementation details and only exposing the necessary information.

Important Points

  • Data abstraction is a programming technique used to simplify complex programs by breaking down large objects into smaller, more manageable chunks.
  • It is achieved by hiding the implementation details and only exposing the necessary information to the outside world.
  • Data abstraction is useful for creating modular and scalable code.

Summary

Data abstraction is an important programming technique that allows us to simplify complex programs by breaking down large objects into smaller, more manageable chunks. It is achieved by hiding the implementation details and only exposing the necessary information to the outside world. This technique is useful for creating modular and scalable code.

Published on: