C++ Programming

Constructor

C plus plus example for decimal to binary using constructor

11/13/2019
0 views
decimal-to-binary.cppCPP
/* Decimal to Binary */
#include<iostream>
using namespace std;

class binaryToDecimal {

	/* By default private variables */
	int binary;

	public:
		/* Constructor declaration */
		binaryToDecimal(int decimal) {
			int i = 1;
			binary = 0;
			while(decimal != 0) {
				binary += (decimal % 2) *i;
				i *= 10;
				decimal /= 2;
			}
		}

		/* Function prototype declaration */
		void display();
};

/* Member function definition outside class */
void binaryToDecimal :: display() {

	/* Access private variable */
	cout << "Binary value is: " << binary << endl;
}

int main() {
	int decimal;
	cout << "Welcome to Decimal to Binary converter" << endl;
	cout << "Enter a Decimal number:" << endl;
	cin >> decimal;

	/* Constructor called explicitly */
	binaryToDecimal btod = binaryToDecimal(decimal);
	btod.display();
	return 0;
}



/* Output */
Welcome to Decimal to Binary converter
Enter a Decimal number:
8

Binary value is: 1000
cppconstructordecimal to binary

Related Examples

Mashable is a global, multi-platform media and entertainment company For more queries and news contact us on this
Email: info@mashablepartners.com