Hi everyone,

I am stuck in writing Bank Account program. I want that if user wants to create an account, BankAccount class object is created. Then after this i call to its methods such as getBalance() to get the balance in the account. But its not working and I am getting error.

#include <iostream>
#include <string>

class BankAccount
{
    protected:
        double balance;

    public:
        BankAccount()
        {
            balance = 0.0;
        }

        BankAccount(double b)
        {
            balance = b;    
        }

        double getBalance()
        {
            return balance;
        }
};

int main()
{

    string input;
    double bal;

    cout <<"Do you want to create an account ??"<<endl;
    cin >> input;

    if(input == "y")
    {
        cout <<"\nYour account has been created !"<<endl;
        cout <<"Specify your amount to deposite :"<<endl;
        cin >> bal;

        BankAccount b1(bal);
    }

    cout <<"Your initial balance is : "<<b1.getBalance() <<"."<<endl; //line of error


return 0;
}

Error is undefined symbol b1. Please help to resolve this error but I need the same logic by asking user to create account in main, Thanks.

The simple reason for the error is that the scope in which BankAccount b1 is valid, ends with the closure of your if (input == "y") block.

Here's your code with a few minor alterations.

class BankAccount
{
    protected:
        double balance;

    public:
        BankAccount()
        {
            balance = 0.0;
        }

        BankAccount(double b)
        {
            balance = b;
        }

        void Deposit(double b)
        {
            balance += b;    
        }

        double getBalance()
        {
            return balance;
        }
};

int main()
{
    BankAccount b1; // default constructor called
    string input;
    double bal;

    cout <<"Do you want to create an account (y/n) ?"<<endl;
    cin >> input;

    if(input == "y")
    {
        cout <<"\nYour account has been created !"<<endl;
        cout <<"Specify your amount to deposit :"<<endl;
        cin >> bal;

        b1.Deposit(bal);
        cout << "Your initial balance is : "<< b1.getBalance() << "." << endl;
    }
    cin.ignore(90, '\n');
    getchar();

    return 0;
}

I'll leave it to you to handle the precision of the displayed double variables. What happens if I deposit or open an account with a negative amount of money? It's a good idea to validate any user input, so take that into consideration when you're coding.

This question has already been answered. Start a new discussion instead.