Search code examples
c++class-constructorsinherited-constructors

Invoking base class 2 argument constructor into subclass one argument constructor


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


Solution

  • 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) {}