Thu Nov 21 2019

Public Inheritance

File Name: public-inheritance.cpp

/* Binary to Hex using Public Inheritance */
#include<iostream>
using namespace std;

class todecimal {

	/* Private variable; not inheritable */
	int decimal;

	/* Public members; ready for inheritance */
	public:
		todecimal(int binary) {
			int reminder, i = 1;
			decimal = 0;
			while(binary != 0) {
				reminder = binary % 10;
				decimal += reminder * i;
				i *= 2;
				binary /= 10;
			}
	
		}
	
		inline int get_decimal() {
			return decimal;
		}
	
		inline void display_decimal() {
			cout << "Decimal: " << get_decimal() << endl;		
		}

};

/* Inherit parent class into child class using ':' */
/* public derivation */
class tohex : public todecimal {
	int i, value, decimal;
	char hex[20];
	public:

		/* Call constructor "todecimal" */
		tohex(int binary) : todecimal(binary) {
			i = 0;
			decimal = get_decimal();
			while(decimal != 0) {
				value = (decimal % 16);
				switch(value) {
					case 10:
						hex[i] = 'A';
						break;
					case 11:
						hex[i] = 'B';
						break;
					case 12:
						hex[i] = 'C';
						break;
					case 13:
						hex[i] = 'D';
						break;
					case 14:
						hex[i] = 'E';
						break;
					case 15:
						hex[i] = 'F';
						break;
					default:
						hex[i] = value + '0';
						break;
				}
				decimal /= 16;
				i++;
			}
			hex[i] = '\0';
		}

		inline void display_hex() {
			int counter = 0;
			cout << "Hex: ";
			while(hex[counter] != '\0')
				counter++;
			for(int i = counter-1; i >= 0; i--)
				cout << hex[i];
			cout << endl;
		}
};

int main() {
	int binary;
	cout << "Please enter a Binary number:" << endl;
	cin >> binary;
	tohex hex(binary);

	/* Access parent member function by public derivation */
	hex.display_decimal();
	hex.display_hex();
	return 0;
}


/* Output */
Please enter a Binary number:
10001

Decimal: 17
Hex: 11
Reference:

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.