Answer to Question #214938 in C++ for Hemambar

Question #214938

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.


1
Expert's answer
2021-07-08T01:32:44-0400
#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;
}

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