user1656421
user1656421

Reputation:

Function returns undesired value

This is my first time posting to this site, therefore I would appreciate all criticisms in a constructive manner. I am learning to write Object Oriented programming with C++ and decided to make a trivial simulation of an ATM machine that takes in user input and processes it (i.e makeDeposit, checkBalance, etc.).

My Problem: BankAccount method: makeDeposit end up changing the output of getBalance() to prefix with a zero: for example: makeDeposit(10) will change getBalance() from 0 -> 010.

`//BankAccout.h
#ifndef BANK_ACCOUNT_H
#define BANK_ACCOUNT_H
#include <string>
class BankAccount {

private:
    float m_accountBalance;
public:
    BankAccount ();
    float getBalance();

    /*Can I pass by value or would reference be necessary?*/
    void makeDeposit(BankAccount&, int);

};

#endif`



   //BankAccout.cpp
#include "BankAccount.h"

#include <iostream> //remove once done
using namespace std; //remove once done

BankAccount::BankAccount () {
    m_accountBalance = 0;
}

float BankAccount::getBalance() {
    return m_accountBalance;
}

//increment the object balance based on ammount
void BankAccount::makeDeposit(BankAccount &bao, int deposit_amount) {
    bao.m_accountBalance += deposit_amount;
}



int main () {
    BankAccount b1;
    cout << b1.getBalance(); //returns 0
    b1.makeDeposit (b1,1); //returns 01
    cout << b1.getBalance();
    //Ex.
    //makeDepost(b2, 10);
    //b2.getBalance(); will retrun 010

    return 0;
}

Any tips would also be much appreciated as I am about to take the roughest Data Structures course with little experience with object oriented programming.

Also, could someone explain to me what subversion is and how it is used.

Upvotes: 3

Views: 149

Answers (2)

m4tx
m4tx

Reputation: 4531

You just print the 0 value to the console, then add the 1 to the balance and again prints the balance to the console. Result? 01.

How to avoid it? Add << endl to the end of the every cout. You will print every value in separate line then. Example:
cout << b1.getBalance(); change to cout << b1.getBalance() << endl;

Your second question (altough it's not related with the first one):
Subversion (called also SVN) is a software versioning system. You can do backups often with it and - before everything - you can work with your project collaboratively with your team. More info: http://en.wikipedia.org/wiki/Apache_Subversion

Upvotes: 6

Rapptz
Rapptz

Reputation: 21317

You're not printing a new line so it concentrates it together as 0 then 1 for 01. To fix it call endl; after cout << b1.getBalance();

Like so:

int main () {
    BankAccount b1;
    cout << b1.getBalance() << endl; //returns 0
    b1.makeDeposit (b1,1); //returns 01
    cout << b1.getBalance() << endl;
    //Ex.
    //makeDepost(b2, 10);
    //b2.getBalance(); will retrun 010

    return 0;
}

Upvotes: 2

Related Questions