Answer to Question #187606 in C++ for RAHUL KUMAR

Question #187606

Write a program which has a class called binary which has a character array to store a binary string. The class decimal derives from class binary and contains an integer data member. Another class called hexadecimal also derives from binary. Each class should contain constructors and appropriate data members to input and display the elements. The display function of binary class displays the binary equivalent, hexadecimal class’s display function displays hexadecimal equivalent whereas decimal class’s display function displays the decimal equivalent.


1
Expert's answer
2021-05-04T11:31:38-0400
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
class Binary{
    protected:
        char c[32];
    public:
        Binary(int n){
            string s = bitset<32>(n).to_string();
            for(int i = 0; i < s.length(); i++) c[i] = s[i];
        }
        virtual void display(){
            cout<<"Binary: ";
            int i = 0;
            while(c[i] == '0'){ 
                i++;
            }
            for(i; i < 32; i++) cout<<c[i];
            cout<<endl;
        }
};
class Octal: public Binary{
    int octal[100];
    public:
        int i = 0;
        Octal(int n): Binary(n){
            while (n != 0) {
                octal[i] = n % 8;
                n = n / 8;
                i++;
            }
        }
        void display(){
            cout<<"Octal: ";
            for (int j = i - 1; j >= 0; j--)
                cout << octal[j];
            cout<<endl;
        }
};
class Decimal: public Binary{
    int decimal;
    public:
        Decimal(int n): Binary(n){
            decimal = n;
        }
        void display(){
            cout<<"Decimal: "<<decimal<<endl;
        }
};
int main(){
    cout<<"Input number in decimal: ";
    int n; cin>>n;


    Binary *binary = new Binary(n);
    binary->display();


    Binary *decimal = new Decimal(n);
    decimal->display();


    Binary *octal = new Octal(n);
    octal->display();
    
    return 0;
}

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