Answer to Question #213282 in C++ for Hemambar

Question #213282

Create a class called InputData. It has two private data members data_a and data_b. Set the

values of these two data members by using two public functions get_a() and get_b(). Derive a class

called Arith_Unit from InputData. It contains the functions add(),sub(), mul(),div() to perform

arithmetic operations on data_a and data_b. Derive a class Logic_Unit from InputData. It

contains the functions and(), or() and xor() to perform logical operations on data_a and data_b.

Finally derive a class called ALUnit from Arith_Unit and Logic_Unit classes. It has to perform

arithmetic and logical operations according to the given codes. Choose code 0 to code 6 to perform

the said seven operations. Write sample program to test the ALU class.


1
Expert's answer
2021-07-28T02:59:32-0400
#include <iostream>

using namespace std;

class InputData
{
private:
    int data_a;
    int data_b;
public:
    InputData(int dataA, int dataB) : data_a(dataA), data_b(dataB) {}

    int get_a() {return data_a;}
    int get_b() {return data_b;}
};


class Arith_Unit : public InputData {

public:
    Arith_Unit(int dataA, int dataB) : InputData(dataA, dataB) {}

    int add() {
        return get_a()+get_b();
    }
    int sub() {
        return get_a()-get_b();
    }
    int mul() {
        return get_a()*get_b();
    }
    int div() {
        return get_a()/get_b();
    }
};

class Logic_Unit : public InputData {

public:
    Logic_Unit(int dataA, int dataB) : InputData(dataA,dataB) {}
    bool And() {
        return get_a() & get_b();
    }
    bool Or() {
        return get_a() | get_b();
    }
    bool Xor() {
        return get_a() ^ get_b();
    }
};

class ALUnit : public Arith_Unit, public Logic_Unit
{
private:
    int code;
public:
    ALUnit(int code, int dataA, int dataB) : code(code), Arith_Unit(dataA, dataB), Logic_Unit(dataA, dataB) {}

    void calc() {
        if (code == 0) cout << add() << '\n';
        else if (code == 1) cout << sub() << '\n';
        else if (code == 2) cout << mul() << '\n';
        else if (code == 3) cout << div() << '\n';
        else if (code == 4) cout << And() << '\n';
        else if (code == 5) cout << Or() << '\n';
        else if (code == 6) cout << Xor() << '\n';
    }
};

int main()
{
    int data_a = 10, data_b = 23, code = 2;
    ALUnit foo(code, data_a, data_b);
    foo.calc();

    return 0;
}

Output:
230

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS