Home > Blockchain >  Why Removing the default constructor is giving error in the compilation of code in c ?
Why Removing the default constructor is giving error in the compilation of code in c ?

Time:12-13

#include <iostream>
 
using namespace std;

class BankDeposit {
    int principal;
    int years;
    float interestRate;
    float returnValue;

    public:
    BankDeposit() { } //This is line number 12
    
    BankDeposit(int p, int y, float r); // r can be a value like 0.04
    
    BankDeposit(int p, int y, int r); // r can be a value like 14
    
    void show();
};

BankDeposit::BankDeposit(int p, int y, float r) {
    principal = p;
    years = y;
    interestRate = r;
    returnValue = principal;

    for (int i = 0; i < y; i  ) {
        returnValue = returnValue * (1   interestRate);
    }
}

BankDeposit::BankDeposit(int p, int y, int r) {
    principal = p;
    years = y;
    interestRate = float(r)/100;
    returnValue = principal;

    for (int i = 0; i < y; i  ) {
        returnValue = returnValue * (1 interestRate);
    }
}

void BankDeposit::show() {
    cout << endl << "Principal amount was " << principal
         << ". Return value after " << years
         << " years is "<<returnValue << endl;
}

int main() {
    BankDeposit bd1, bd2, bd3;
    int p, y;
    float r;
    int R;
    
    // bd1 = BankDeposit(1, 2, 3);
    // bd1.show();

    cout << "Enter the value of p y and R" << endl;
    cin >> p >> y >> R;
    bd2 = BankDeposit(p, y, R);
    bd2.show();

    return 0;
}

Why removing or commenting out the code in line number 12 is giving error in running the code? But as I know that we are making our own constructor so what is the need of having default constructor in the code? Also not including the default constructor in the code is why giving the errors?

CodePudding user response:

BankDeposit bd1, bd2, bd3;

This line where you are creating an object of a class requires a constructer which should be a default constructer as you have not passed any parameters.

Edit : Just saw the comments under the question they have already explained it, furthermore this question can be easily resolved by reading the error message. you can learn about constructers here : here

CodePudding user response:

If you implement a parameterized constructor in your class, the rule is that you also must have the default constructor in your class. That is why your code fails. If you didn't have any constructor other than the default constructor, the code wouldn't fail even if you didn't have the default constructor in your code.

The things is that first you're overriding the compiler with creating a parameterized constructor, but then you're trying to create objects without parameters and for that you need the default constructor, so you must implement it.

  • Related