Wed Nov 20 2019

Inheritance

C++ Programming2471 views

File Name: inheritance.cpp

/* Binary to Octal using 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 ':' */
/* Private derivation by default */
class tooctal : todecimal {
	int octal, i, decimal;
	public:
		/* Call constructor "todecimal" */
		tooctal(int binary) : todecimal(binary) {
			decimal = get_decimal();
			i = 1;
			octal = 0;
			while(decimal != 0) {
				octal += (decimal % 8) *i;
				i *= 10;
				decimal /= 8;
			}
		}

		inline void display() {
			display_decimal();
			cout << "Octal: " << octal << endl;
		}
};

int main() {
	int binary;
	cout << "Please enter a Binary number:" << endl;
	cin >> binary;
	tooctal octal(binary);
	octal.display();
	return 0;
}



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

Decimal: 10
Octal: 1
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.