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.
#include <iostream>
using namespace std;
#include <math.h>
class Binary{
public:
char bin[10]="101101";
Binary(){
cout<<"\nThe binary equivalent is: "<<bin;
}
};
class Decimal: public Binary{
private:
int num;
public:
Decimal(){
int n=atoi(bin);
int dec_value = 0;
int base = 1;
int temp = n;
while (temp) {
int last_digit = temp % 10;
temp = temp / 10;
dec_value += last_digit * base;
base = base * 2;
}
cout<<"\n"<<"The decimal equivalent is: "<<dec_value;
}
};
class Octal: public Binary{
private:
int oct;
public:
Octal(){
int octalNumber = 0, decimalNumber = 0, i = 0;
int binaryNumber=atoi(bin);
while(binaryNumber != 0)
{
decimalNumber += (binaryNumber%10) * pow(2,i);
++i;
binaryNumber/=10;
}
i = 1;
while (decimalNumber != 0)
{
octalNumber += (decimalNumber % 8) * i;
decimalNumber /= 8;
i *= 10;
}
cout<<"\n"<<"The octal equivalent is: "<<octalNumber;
}
};
int main(){
Decimal d;
Octal oc;
return 0;
}
Comments
Leave a comment