Search code examples
c++semantics

C++ Semantic issue: "'use of undeclared identifier 'balance'"


I am new to C++ and using Xcode and I am having an issue, in my main .cpp file Account.cpp the code is-

#include <iostream>

using namespace std;
#include "Account.h"
Account::Account()

{
    double balance=0;
    balance=0;
}
Account getbalance()
{
    return balance;
}

void deposit(double amount)
{
    balance+=amount;
}
void withdraw(double amount)
{
    balance-=amount;
}
void addInterest(double interestRate)
{
    balance=balance*(1+interestRate);
}

I think I missed something but I'm not sure where, any help would be appreciated thank you.

**The header file Account.h is-

#include <iostream>
using namespace std;
class Account
{
private:
    double balance;
public:
    Account();
    Account(double);
    double getBalance();
    void deposit(double amount);

    void withdraw(double amount);
    void addInterest(double interestRate);
};

Solution

  • Write the constructor the following way

    Account::Account()
    {
        balance = 0.0;
    }
    

    I suppose that balance is a data member of type double of class Account.

    Or you can write

    Account::Account() : balance( 0.0 ) {}
    

    And all these function definitions if the functions are class member functions must look at least like

    double Account::getBalance()
    {
        return balance;
    }
    
    void Account::deposit(double amount)
    {
        balance+=amount;
    }
    void Account::withdraw(double amount)
    {
        balance-=amount;
    }
    void Account::addInterest(double interestRate)
    {
        balance=balance*(1+interestRate);
    }
    

    Also it seems that you forgot to define the constructor with a parameter.

    Account::Account( double initial_balance ) : balance( initial_balance ) {}