I think I need to perform a multidimensional array or vector within it will define account and balance. Such as I defined {acctnum=44421, balance=0} by default the balance would be 0, and then I want to define another account {acctnum=55531, balance=""}. With each of these I need to take the first account with deposit and perform a withdrawal 10 then deposit 6. Then go to second deposit 3 and then deposit 5. Then display the intial deposit, then after withdrawal and after second deposit and what the account is after these actions.
header
#ifndef account_h_
#define account_h_
#include <iostream>
#include <string>
#include <account>
using std::account;
class account
{
public:
account();
account(const std::string acctnum);
~account();
//----------------------------------------------------
//account number
const std:string get_acctnum() const{
return m_acctnum;
}
//----------------------------------------------------
//deposit
void deposit(float amt){
m_balance += amt;
}
//----------------------------------------------------
//withdraw
void withdraw(float amt){
m_balance -= amt;
}
//----------------------------------------------------
//current balance
const double get_balance() const{
return m_balance;
})
//----------------------------------------------------
//display string
const std::string asString() const;
private:
//----------------------------------------------------
//account number
int m_acctnum;
//----------------------------------------------------
//balance
double m_balance;
//----------------------------------------------------
//after deposit or withdrawal
void inc(const double d) {
m_reading += d;
}
};
#endif
program
#include <iostream>
#include <string>
#include <stdlib.h>
#include "account.h"
using namespace std;
//----------------------------------------------------
//bank account default balance
account::account(){
m_balance = 0;
m_acctnum = "???";
}
account::account(const std::string acctnum){
m_balance = 0;
m_acctnum = acctnum;
}
account::~account(){
}
//----------------------------------------------------
//deposit
void account::deposit(double amount){
balance = balance + amount;
}
//----------------------------------------------------
//withdraw
void account::withdraw(double amount){
if(amount < balance ){
std::cout << "Debit amount exceeded account balance."
<< amount << endl;
}
else if(amount < 0){
std::cout <<"The withdrawel you've enter is defined as negative."
<< amount << endl;
}
else{
balance = balance - amount;
}
}
//----------------------------------------------------
//get balance
double account::get_balance() const{
return balance;
}
//----------------------------------------------------
//display
const std::string account::asstring() const{
ostringstream oss;
oss << "Account Num: " << m_acctnum <<
" Balance: " << m_balance;
return oss.str();
}
Test Program This is where I am having trouble in creating the program to do this. I think I need an array, maybe multidimensional array and access to the balance so I can perform deposits and withdrawals on??
#include <iostream>
#include <string>
#include "account.h"
void main(){
account::account[][2] = {
{44421, 20},
{55531, }
};
for (int row = 0; row < 2; ++row)
{
for (int col = 0; col < 2 ; ++col)
{
account::deposit[col]
}
}
}
You have multiple problems with your code.
//account number
int m_acctnum;
Your class member is an int.
const std:string get_acctnum() const{
return m_acctnum;
}
account::account(const std::string acctnum){
m_balance = 0;
m_acctnum = acctnum;
}
But your methods think it's a std::string. You cannot assign a std::string to an int. Similarly, you cannot convert an int directly to a std::string.
I'm sure your compiler reported all of these as errors. Did you understand your compiler's error messages? Here's a simple question, do you think that the following piece of code is valid:
int n="the rain in spain falls mainly in the plane";
Of course not, yet this is what you're trying to do, and, of course, the compiler can't be happy about it.
account::account[][2] = {
{44421, 20},
{55531, }
};
It's not clear what this is supposed to be, either. Each instance of an class is instantiated by either explicitly invoking the class's constructor, or using the class's default constructors; and then assigning it to a variable. Class instances are not instantiated by manually initializing private class members.
Your account class has a default constructor, and a constructor that takes one parameter. Your class does not have any constructors that take two parameters, so this is not a valid initialization.
Additionally, a class is constructed by giving the class's name, and the name of the class instance, and not by explicitly invoking the class's constructor.
account::deposit[col]
account::deposit() is a class method. It is not a static class function that can be invoked like that. Additionally, parameters to either a class method, or a static class functions are passed using parenthesis, not brackets.
Additionally, the deposit() method takes a parameter that's described as a "balance". It is not a "column number" type of a parameter.
Related
First and foremost I'd like to apologize for the magnitude of code I'm dumping. I'm writing some code that allows the user to withdraw and deposit money into an account, the code also calculates the interest rate of the account and the number of withdrawals and deposits etc. I get on error when I try to call the base class functions to the child functions, "no matching constructor." I can't seem to find a problem with the constructors on my own. Can anyone help?
Account.cpp
#include "Account.h"
#include <iostream>
#include <iomanip>
using namespace std;
//overloaded constructor
Account::Account(double accBal, double annIntRate){
accBal = accBal;
annIntRate = annIntRate;
};
//deposit base class function
int Account::deposit(double accBal, int numWithdrawal)
{
cout << "Enter deposit: "<< endl;
double depos;
cin >> depos;
accBal += depos;
numDepos ++;
return accBal;
}
//withdraw base class function
void Account::withdraw(double accBal, int numWithdrawal)
{
double amount;
cin >> amount;
accBal -= amount;
numWithdrawal ++;
}
//interest rate calculation
void Account::calcInt(double accBal, double annIntRate)
{
double monthlyIntRate = annIntRate/2;
double monthlyInt = accBal * monthlyIntRate;
accBal += monthlyInt;
}
Account.h
#ifndef ACCOUNT_H
#define ACCOUNT_H
class Account
{
//variable declarations
private:
int accNum;
double accBal;
int numWithdrawal;
int numDepos;
double annIntRate;
double monthServCharg;
public:
Account(double, double); //overloaded constructor
virtual int deposit(double, int); //base class deposit declaration
virtual void withdraw(double, int); //base class withdraw declaration
virtual void calcInt(double, double); //updates interest rate
void setAccNum(int); //setter
int getAccNum(){return accNum;} //getter
void setAccBal(double);//setter
double getAccBal(){return accBal;}//getter
void setNumWithdrawal(int);//setter
int getNumWithdrawal(){return numWithdrawal;}//getter
void setNumDep(int);//setter
int getNumDep(){return numDepos;}//getter
void setAnnIntRate(double);//setter
double getAnnIntRate(){return annIntRate;}//getter
void setMonthServCharg(double); //setter
double getMonthServCharg(){return monthServCharg;}//getter
};
#endif
SavingsAccount.cpp
#include "SavingsAcc.h"
#include "Account.h"
#include <iostream>
using namespace std;
//status constructor
SavingsAccount::SavingsAccount(bool status)
{
status = false;
}
//deposit money function
void SavingsAccount::deposit(bool status, double accBal, int numDepos)
{
Account obj;
obj.deposit(accBal); //PROBLEM
if (accBal > 25.00)
status = true;
else
status = false;
}
//withdraw money child function, updates account status, service charges, interest rate etc
void SavingsAccount::withdraw(double accBal, int numWithdrawal, double annIntRate, double monthServCharg)
{
double amount;
if (accBal <= 25.00)
cout << "Balance too low, withdrawals cannot be made at this time"<<endl;
else
{
do
{
Account obj;
obj.withdraw(numWithdrawal); // PROBLEM
if (numWithdrawal > 4)
monthServCharg += 1;
if (accBal < 25.00)
{annIntRate += 0.01;}
}
while (amount > accBal);
cout << "Insufficient funds!";
}
}
//outputs the report of account
void SavingsAccount::accountReport(int accNum, bool status, int numWithdrawal, int numDepos, double monthServeCharg, double accBal)
{
cout << "====ACCOUNT STATUS===="<<endl;
cout << "Account number: "<< accNum <<endl;
if (status == true) //status
cout << "Satus: Active" << endl;
else
cout <<"Status: Inactive" << endl;
cout << "Total deposits: "<< numDepos << endl;
cout << "Total withdrawals" << numWithdrawal << endl;
cout << "Service charges: "<< monthServeCharg << endl;
cout << "Balance: "<<accBal<<endl;
}
SavingsAccount.h
#ifndef SAVINGSACC_H
#define SAVINGSACC_H
#include <iostream>
class SavingsAccount: public Account
{
private:
bool status; //status variable
public:
SavingsAccount(bool); // constuctor
void deposit(bool, double, int); // deposit function
void withdraw(double, int, double, double); //withdraw function
void accountReport(int, bool, int, int, double, double ); // full report of account
};
#endif
The constructor
Account(double, double); //overloaded constructor
is actually not overloading constructor but invalidating the default constructor.
To use this constructor, passing values for the arguments when constructing SavingsAccount like
SavingsAccount::SavingsAccount(bool status) : Account(42, 334)
{
status = false;
}
is required.
Also the line
obj.deposit(accBal); //PROBLEM
is causing error because the class Account doesn't have function deposit that takes only one argument. You should delete the line or pass right number of arguments to resolve this error.
I can't seem to figure out what is going on with this GPA calculator program I'm trying to build. The problem is in the printTranscript method of Student class. The method calls getGPA method of the same class, which returns a double, the output is some massive number instead of a standard GPA.
main.cpp:
#include <iostream>
#include "Student.cpp"
using namespace std;
int main(){
Student stud("Lebron", 23232);
stud.addCourse("Passing", 3, 'A');
stud.addCourse("Finals Record", 4, 'D');
stud.printTranscript();
return 0;
}
Student.h:
#include "Course.h"
#include <vector>
class Student{
private:
string name;
int studentID;
vector<Course> courses;
public:
Student(){
name = "No Name";
studentID = 0;
}
Student(string n, int ID){
name = n;
studentID = ID;
}
string getName(){
return name;
}
void setName(string n){
name = n;
}
int getID(){
return studentID;
}
void setID(int ID){
studentID = ID;
}
void addCourse(string, int, char);
void addCourse(Course);
double getGPA();
void printTranscript();
};
Student.cpp:
#include "Student.h"
void Student::addCourse(string name, int credits, char grade){
courses.push_back(Course(name,credits,grade));
}
void Student::addCourse(Course c){
courses.push_back(c);
}
double Student::getGPA(){
double gradePoints, totalCredits;
for(int i = 0; i < courses.size(); i++){
if(courses[i].getGrade() == 'A'){
gradePoints += (4.0 * courses[i].getCredits());
totalCredits += courses[i].getCredits();
}
else if(courses[i].getGrade() == 'B'){
gradePoints += (3.0 * courses[i].getCredits());
totalCredits += courses[i].getCredits();
}
else if(courses[i].getGrade() == 'C'){
gradePoints += (2.0 * courses[i].getCredits());
totalCredits += courses[i].getCredits();
}
else if (courses[i].getGrade() == 'D'){
gradePoints += (1.0 * courses[i].getCredits());
totalCredits += courses[i].getCredits();
}
}
return (gradePoints / totalCredits);
}
void Student::printTranscript(){
cout << "Transcript for: " << name << endl;
cout << "============================" << endl;
for(int i = 0; i < courses.size(); i++){
cout << "Course: " << courses[i].getID() << endl;
cout << "Grade: " << courses[i].getGrade() << endl;
cout << endl;
}
cout << "Overall GPA: " << getGPA() << endl;
}
Course.h:
#include <iostream>
#include <string>
using namespace std;
class Course{
private:
string courseID; // Course name
int numCredits; // Instructor
char letterGrade; // Textbook
public:
Course(string ID, int credits, char grade){ // Assign the course name.
courseID = ID;
numCredits = credits;
letterGrade = grade;
}
string getID(){
return courseID;
}
void setID(string ID){
courseID = ID;
}
int getCredits(){
return numCredits;
}
void setCredits(int credits){
numCredits = credits;
}
char getGrade(){
return letterGrade;
}
void setGrade(char grade){
letterGrade = grade;
}
};
Sorry for the long bit of code, but I can't seem to figure out why output in main is giving me:
Transcript for: Lebron James
============================
Course: Passing
Grade: A
Course: Finals Record
Grade: D
Overall GPA: 2.2321e+230
If I cout stud.getGPA in the main class as a separate statement, it works fine. What explains the massively large number being output here when called from another method of the same class, and how is this fixed?
Sorry for the long code, but I didn't want to miss anything, as I am still at the beginning stages of C++.
From dcl.init/7:
To default-initialize an object of type T means:
If T is a (possibly cv-qualified) class type, constructors are considered. The applicable constructors are enumerated
([over.match.ctor]), and the best one for the initializer () is chosen
through overload resolution. The constructor thus selected is called,
with an empty argument list, to initialize the object.
If T is an array type, each element is default-initialized.
Otherwise, no initialization is performed.
You are directly doing some operation +=:
totalCredits += courses[i].getCredits();
but forget to initialize the variable. Don't assume everything will be set to zero initially.
Thus, Initialize totalCredits to 0.0.
Adding -Wuninitialized:
As suggested by #1201ProgramAlarm, use -Wuninitialized to flag uninitialized variables.
warning: 'totalCredits' may be used uninitialized in this function [-Wuninitialized]
If you want to treat warnings as errors, just add the flag -Werror
Here's my code and the errors I'm receiving - any help would be appreciated.
There's something wrong with getNextAcountNumber. I have tried to assign the value of account ID but it has not worked since it is a private member.
Error 1 error LNK2019: unresolved external symbol "private: int __thiscall Account::getNextAccountNumber(void)const " (?getNextAccountNumber#Account##ABEHXZ) referenced in function "public: __thiscall Account::Account(class std::basic_string,class std::allocator >,double)" (??0Account##QAE#V?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##N#Z) H:\programming\AccountClass\AccountClass.obj AccountClass
H:\programming\AccountClass\Debug\AccountClass.exe : fatal error LNK1120: 1 unresolved externals
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include "Account.h"
using namespace std;
int main()
{
Account acct01;
Account acct02("Harold M. Ferguson", 2000);
Account acct03("Elise Janet Simmons", 3500);
Account acct04("James Holder", 0);
cout << endl << "Account information - initial" << endl;
acct01.displayAccountInfo(); // show account information - initial values
acct02.displayAccountInfo();
acct03.displayAccountInfo();
acct04.displayAccountInfo();
acct01.setAccountHolder("Mary A. Tarleton");
acct01.setBalance(542.39);
acct04.setAccountHolder("James Ellis Holder");
acct04.setBalance(1990.75);
cout << endl << "Account information after changes" << endl;
acct01.displayAccountInfo(); // show account information after changes
acct02.displayAccountInfo();
acct03.displayAccountInfo();
acct04.displayAccountInfo();
acct01.depositAmount(455); // make deposits
acct02.depositAmount(-19.95); // negative deposit not allowed - set to zero
acct03.depositAmount(4365.27);
acct04.depositAmount(95.63);
cout << endl << "Account information after deposits" << endl;
acct01.displayAccountInfo(); // show account information after deposits
acct02.displayAccountInfo();
acct03.displayAccountInfo();
acct04.displayAccountInfo();
acct01.withdrawAmount(37.39);
acct02.withdrawAmount(-475.25); // withdrawal may be positive or negative (absolute value)
acct03.withdrawAmount(0.25);
acct04.withdrawAmount(50.00);
cout << endl << "Account information after withdrawals" << endl;
acct01.displayAccountInfo(); // show account information after withdrawals
acct02.displayAccountInfo();
acct03.displayAccountInfo();
acct04.displayAccountInfo();
cout << endl;
system("pause");
return 0;
}
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include "Account.h"
#include <string>
using namespace std;
Account::Account()
{
accountID = getNextAccountNumber();
accountHolder = "no name";
balance = 0;
}
Account::Account(string name, double amount)
{
accountID = getNextAccountNumber();
accountHolder = name;
balance = amount;
}
int Account::getAccountID() const
{
return accountID;
}
string Account::getAccountHolder() const
{
return accountHolder;
}
double Account::getBalance() const
{
return balance;
}
void Account::setAccountHolder(string name)
{
accountHolder = name;
}
void Account::setBalance(double amt)
{
amt = balance;
}
void Account::depositAmount(double amt)
{
if (amt > 0)
{
balance = +amt;
}
else;
{
balance = balance;
}
}
void Account::withdrawAmount(double amt)
{
balance = balance - amt;
}
void Account::displayAccountInfo() const
{
cout << accountID << accountHolder << balance;
}
#ifndef ACCOUNT_H
#define ACCOUNT_H
#include <string>
using namespace std;
static int accountNumber = 100000; // starting value for account#
class Account
{
public:
Account(); // default constructor
Account(string name, double amount); // constructor with two parameters
int getAccountID() const; // ACCESSOR member functions
string getAccountHolder() const; // return name of account holder
double getBalance() const; // return account balance
void setAccountHolder(string name); // MUTATOR member functions
void setBalance(double amt); // assign amount to balance
void depositAmount(double amt); // add amount to balance
void withdrawAmount(double amt); // subtract absolute value of amount from balance
// HELPER member functions
void displayAccountInfo() const; // display account information
private:
int getNextAccountNumber() const; // get next account# (pre-increment account number)
// private DATA members
int accountID; // account# identifier
string accountHolder; // name of account holder
double balance; // account balance
};
// accountID = ++accountNumber
#endif
This problem is not related to the function being private - it is being called by the constructor(s), which have access to the private members of the class.
Both #DrewDormann and #PaulMcKenzie seem correct in the comments - you have (at least listed) no implementation for Account::getNextAccountNumber()
This should likely be in the second code snippet you have posted (likely Account.cpp, or similar)
Consider adding something like
int Account::getNextAccountNumber()
{
return accountNumber++;
}
However, this would seem in nature to be a function independent of anything even remotely related to any individual given Account, so consider making it a freestanding function. (i.e. not a member of the Account class)
Then you'd just have
int getNextAccountNumber()
{
return accountNumber++;
}
but in that case, you'd have to modify the header (perhaps Account.h?) to remove the member function. Otherwise, you'll still get the linker error you're currently hitting.
Edit: The function is declared as const, so you need the const specifier.
int Account::getNextAccountNumber() const
{
return accountNumber++;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I don't know why but when i create an object with my class and use the default constructor, when i try to pass the variable named cash to the accessor user2.setCash(cash) which purpose is to primary set cash equal to new_cash, it gives a large value like 1.222256e+461 or something like that. Why does that happen? If i use my overload constructor it works fine.
main.cpp
#include <iostream>
#include <string>
#include "Bank.h"
using namespace std;
int main()
{
string name;
int id;
double cash;
bank user2;
cout << "\n\nPlease type your name: ";
getline(cin >> ws, name);
user2.setName(name);
cout << "Enter an id number: ";
cin >> id;
user2.setID(id);
cout << "Enter your cash: ";
cin >> cash;
cout << cash << endl;
user2.setCash(cash);
cout << "\nAlright " << user2.getName() << ", current cash: " << user2.getCash();
cout << "\nChoose how much would you like to Deposit: ";
cin >> cash;
user2.deposit(cash);
cout << "New amount is: " << user2.getCash() << " For user ID: " << user2.getID() << "\n\n";
bank::printStatic();
return 0;
}
Bank.h
#ifndef BANK_H
#define BANK_H
#include <iostream>
#include <string>
using namespace std;
class bank
{
public:
// Default Constructor
bank();
// Overload Constructor
bank(string, int, double);
// Destructor
~bank();
// Accessor Functions
string getName() const;
int getID() const;
double getCash() const;
// Mutator Functions
void setName(string);
void setID(int);
void setCash(double);
// Functions
void withdraw(double);
void deposit(double);
static void printStatic();
private:
// Member Variables
string new_name;
int new_id;
double new_cash;
// Static Member Variables
static int num_of_accounts;
static double total_cash;
};
#endif
Bank.cpp
#include "Bank.h"
// Static Variables
int bank::num_of_accounts = 0;
double bank::total_cash = 0.0;
// Default Constructor
bank::bank()
{
int new_id = 0;
double new_cash = 0.0;
++num_of_accounts; // New object is created e.g. a person so total accounts must be increased.
}
// Overload Constructor
bank::bank(string name, int id, double cash)
{
new_name = name;
new_id = id;
new_cash = cash;
++num_of_accounts; // New object is created e.g. a person so total accounts must be increased.
total_cash += new_cash; // New object is created e.g. a person so his/hers cash must be added to the total cash of the bank.
}
// Destructor
bank::~bank()
{
--num_of_accounts; // When Destructor is called to destroy an object (e.g. a person) then the id must be dropped by 1 cause the person e.g. (left).
total_cash -= new_cash; // And the balance he had to be removed so it is not counted in total cash avaliable in the bank cause he e.g. (left).
}
// Accessor Functions
string bank::getName() const
{
return new_name;
}
int bank::getID() const
{
return new_id;
}
double bank::getCash() const
{
return new_cash;
}
// Mutator Functions
void bank::setName(string name)
{
new_name = name;
}
void bank::setID(int id)
{
new_id = id;
}
void bank::setCash(double cash)
{
cout << new_cash << endl;
total_cash -= new_cash; // We must remove his prior cash which we holded in the total so we can then use the new value suplied.
new_cash = cash;
total_cash += new_cash; // Here we add the new cash (balance) he/she has.
}
void bank::withdraw(double cash)
{
new_cash -= cash;
total_cash -= cash;
}
void bank::deposit(double cash)
{
new_cash += cash;
total_cash += cash;
}
void bank::printStatic()
{
cout << "Total users are: " << num_of_accounts << endl;
cout << "Total cash in bank is: " << total_cash << endl;
}
You need to initialize all primitive type members in the constructor.
Otherwise you get indeterminate values
Also, the non-default constructor is buggy:
// Default Constructor
bank::bank()
{
int new_id = 0;
double new_cash = 0.0;
....
^ sets values of local variables, not the member variables
I'd suggest to use the initilization lists:
// Default Constructor
bank::bank() : new_name(), new_id(0), new_cash(0.0)
{
++num_of_accounts;
}
// Overload Constructor
bank::bank(string name, int id, double cash)
: new_name(name), new_id(id), new_cash(cash)
{
++num_of_accounts;
total_cash += new_cash;
}
You could also combine the two:
bank::bank(string name = "", int id = 0, double cash = 0.0)
: new_name(name), new_id(id), new_cash(cash)
{
++num_of_accounts;
total_cash += new_cash;
}
In your default constructor, you're declaring local variables with the same names as the member variables. Then you're setting these local variables instead of assigning the members. Get rid of the type declarations so they're normal assignments.
bank::bank()
{
new_id = 0;
new_cash = 0.0;
++num_of_accounts; // New object is created e.g. a person so total accounts must be increased.
}
noob here. Having a doubt while doing an exercise from a book.
The doubt is the following: Why if I use a const std::string * as an argument to a method, the compiler sends me the following error: no matching function for call to 'BankAccount::define(const char [11], const char [11], int)' in the client?
If I swap the prototype and definition of the method to accept as an argument a const std::string & (like I did in the constructor) it's no problem for the compiler.
Client:
// usebacnt.cpp --
#include "BankAccount.h"
#include <iostream>
int main()
{
BankAccount john;
BankAccount mary("Mary Wilkinson", "5000000000"); // balance set to 0 because of default argument
john.display();
mary.display();
john.define("John Smith", "4000000000", 26); // error line
mary.deposit(1000.50);
john.withdraw(25);
john.display();
mary.display();
std::cin.get();
return 0;
}
Class declaration:
// BankAccount.h -- Header file for project Exercise 10.1
#ifndef BANKACCOUNT_H_
#define BANKACCOUNT_H_
#include <string>
class BankAccount
{
private:
std::string fullName;
std::string accountNumber;
double balance;
public:
BankAccount(); // default constructor
BankAccount(const std::string &fN, const std::string &aN, double b = 0.0); // constructor with a default argument
void display() const;
void deposit(double amount);
void withdraw(double amount);
void define(const std::string *pfN, const std::string *paN, double b);
};
#endif
Class implementation:
// methods.cpp -- Compile alongside usebacnt.cpp
#include "BankAccount.h"
#include <iostream>
void BankAccount::display() const
{
using std::cout;
using std::ios_base;
ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield); // formatting output and saving original
cout.precision(2);
cout << "Full Name: " << fullName << '\n';
cout << "Account Number: " << accountNumber << '\n';
cout << "Balance: " << balance << "\n\n";
cout.setf(orig);
}
void BankAccount::deposit(double amount)
{
if (amount < 0)
{
std::cout << "You can't deposit a negative number! Amount set to zero.";
amount = 0;
}
balance += amount;
}
void BankAccount::withdraw(double amount)
{
if (amount < 0)
{
std::cout << "You can't withdraw a negative number! Amount set to zero.";
amount = 0;
}
if (balance < amount)
{
std::cout << "You can't withdraw more money than you have. Amount set to zero.";
amount = 0;
}
balance -= amount;
}
void BankAccount::define(const std::string *pfN, const std::string *paN, double b)
{
fullName = *fN;
accountNumber = *aN;
balance = b;
}
// constructors
BankAccount::BankAccount() // default constructor
{
fullName = "empty";
accountNumber = "empty";
balance = 0.0;
}
BankAccount::BankAccount(const std::string &fN, const std::string &aN, double b) // constructor with default argument
{
fullName = fN;
accountNumber = aN;
balance = b;
}
Shouldn't the compiler interpret the literal as a string object (like it does with the reference)? So if I say it's a pointer it should pass the address of the string (its first element).
Any help?
Shouldn't the compiler interpret the literal as a string object (like it does with the reference)?
No. Pointers are not references; smack anyone who tells you that they are.
It all comes down to this: std::string is not a string literal. Therefore, when you pass a string literal to a function that takes a std::string, a temporary std::string that holds the contents of the literal must be created. This is done with the conversion constructor of std::string.
A const& is allowed to be initialized from a temporary, which allows conversion constructors to work their magic. A const* must be a pointer, and you're not supposed to get pointers to temporaries. Therefore, const* cannot be magically filled in by a temporary created from a conversion constructor.
You should use a const std::string & instead of a pointer. Or a std::string value if you have C++11 move constructors available.