Wed Nov 13 2019
Constructor
C++ Programming1208 views
File Name: decimal-to-binary.cpp
/* 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
Reference:
Constructor in C++
Author:Geekboots