write a program for conversion from decimal to binary ,octal and hexadecimal .the program should be developed as follows:
(a).the base class convert has two variables initial and result in which initial is a number before conversion and result is
after conversion.
(b). it has two member functions getinit() and getconv() which return the initial value and converted value respectively.
(c). write a function compute which is a pure virtual function that actually does the conversion.
(d). separate derived classes for hexadecimal ,binary, octal, does the conversion by implementing the function compute.
(e). create the objects for each class using new operator.
(f). use the convert class type pointer to call the compute functions of the derived classes.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Base
{
public:
Base(int init);
virtual ~Base();
int getinit() { return initial; }
string getconv() { return result; }
virtual void compute() = 0;
int initial;
string result;
};
Base::Base(int init) : initial(init)
{
}
Base::~Base()
{
}
class hexadecimal : public Base
{
public:
hexadecimal(int init);
void compute();
};
hexadecimal::hexadecimal(int init) : Base(init)
{
compute();
}
void hexadecimal::compute()
{
std::stringstream ss;
ss << std::hex << getinit();
result = ss.str();
}
class octal : public Base
{
public:
octal(int init);
void compute();
};
octal::octal(int init) : Base(init)
{
compute();
}
void octal::compute()
{
std::stringstream ss;
ss << std::oct << getinit();
result = ss.str();
}
class binary : public Base
{
public:
binary(int init);
void compute();
};
binary::binary(int init) : Base(init)
{
compute();
}
void binary::compute()
{
int temp = initial;
while (temp != 0) { result = (temp % 2 == 0 ? "0" : "1") + result; temp /= 2; }
}
int main()
{
cout << "Enter decimal value: ";
int value;
cin >> value;
Base* base;
base = new hexadecimal(value);
cout << "Hexadecimal: " << base->getconv() << endl;
base = new octal(value);
cout << "Octal: " << base->getconv() << endl;
base = new binary(value);
cout << "Binary: " << base->getconv() << endl;
return 0;
}
Comments
Leave a comment