Abstraction in C++

              It is one of the Object oriented programming concepts which is the basic one. It deals with data. Abstraction shows the essential information to the user and hides the internal details.

For e.g., when you drive a motor bike, you know about bike moving, but the functionality of engine is not known. This is the abstraction.

Types of abstraction:

              Abstraction is classified into two types as follows…

Let us create the c++ program to implement abstraction.

Code:

#include <iostream>

using namespace std;

// Abstract class

class ShapeEg {

public:

    // It is a virtual function

    virtual void find_area() = 0;

    // A non- abstract method

    void displayIt() {

        cout << "This shows a shape." << endl;

    }

};

// Let us Derive a class for Square

class S_Square : public ShapeEg {

private:

    double side;

public:

    S_Square(double s) : side(s) {}

    void find_area() override {

        cout << "Area of the Square is: " << side*side << endl;

    }

};

// Derived class for Rectangle

class S_Rectangle : public ShapeEg {

private:

    double R_l, R_w;

public:

    S_Rectangle(double len, double wid) : R_l(len), R_w(wid) {}

    void find_area() override {

        cout << "Area of the Rectangle is: " << R_l * R_w << endl;

    }

};

int main() {

    double a,b,c;

    cout<<"Enter the side of the square:"<<endl;

    cin>>a;

    cout<<"Enter the length and width of the rectangle:"<<endl;

    cin>>b>>c;

    ShapeEg* s1 = new S_Square(a);

    ShapeEg* s2 = new S_Rectangle(b,c);

    s1->displayIt();

    s1->find_area();

    s2->displayIt();

    s2->find_area();

    delete s1;

    delete s2;

    return 0;

}

Output:

Enter the side of the square:

56.4

Enter the length and width of the rectangle:

6.2 4.5

This shows a shape.

Area of the Square is: 3180.96

This shows a shape.

Area of the Rectangle is: 27.9

This is a simple C++ program to implement abstraction. Abstraction increases security and reduces redundancy. Hope, this code is helpful to you. Keep Coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.