Write a program which has a class named 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 octal 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, octal class’s display function displays octal equivalent whereas decimal class’s display function displays the decimal equivalent.
The program is as follows:
#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: "<<c<<endl;
}
};
class Decimal: public Binary{
int decimal;
public:
Decimal(int n): Binary(n){
decimal = n;
}
void display(){
cout<<"Decimal: "<<decimal<<endl;
}
};
class Octal: public Binary{
int octal;
public:
Octal(int n): Binary(n){
octal = n;
}
void display(){
cout<<"Octal: "<<oct<<octal<<endl;
}
};
int main(){
cout<<"Enter an integer: ";
int x; cin>>x;
Binary binary(x);
binary.display();
Decimal decimal(x);
decimal.display();
Octal octal(x);
octal.display();
return 0;
}
Comments
Leave a comment