Invoking base class 2 argument constructor into subclass one argument constructor

68 Views Asked by At

as title says I am having some problems with invoking base class constructor in subclass constructor

Base:

account.h
    Account(double, Customer*)
account.cpp
    Account::Account(double b, Customer *cu)
    {
    balance = b;
    cust = *cu;
    }

Subclass:

savings.h
    Savings(double);
savings.cpp
    Savings::Savings(double intRate) : Account(b, cu)
    {
    interestRate = intRate;
    }

Error that I am getting is b and cu are undefined. Thanks for help

3

There are 3 best solutions below

5
On BEST ANSWER

Think of how you create a SavingsAccount.

Can you create one using

SavingsAccount ac1(0.01);

If you did that, what would be the balance on that object? Who will be the Customer for that object.

You need to provide the balance as well as the Customer when you create a SavingsAccount. Something like:

Customer* cu = new Customer; // Or get the customer based on some other data
SavingsAccount ac1(100.0, cu, 0.01);

makes sense. You are providing all the data needed for a SavingsAccount. To create such an object, you'll need to define the constructor of SavingsAccount appropriately.

Savings::Savings(double b, Customer *cu, double intRate);

That can be implemented properly with:

Savings::Savings(double b,
                 Customer *cu,
                 double intRate) : Account(b, cu), interestRate(intRate) {}
1
On

In your subclass Savings you need to define b and cu somewhere to pass to constructor of base Account, e.g:

Savings::Savings(double b, Customer* cu, double intRate) : Account(b, cu) {
    interestRate = intRate;
}

Such that the constructor of Savings takes the double and Customer* args required for passing to constructor of base class.

4
On

I think the previous answer is wrong because in Account you don't have to put also intRate. So:

Savings::Savings(double b, Customer* cu, double intRate) : Account(b, cu)
{ interestRate = intRate; }