base class initialization error, no matching constructor - c++

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.

Related

Separate classes into their own definition and implementation files and main in its own file [duplicate]

This question already has answers here:
run a program with more than one source files in GNU c++ compiler
(3 answers)
Closed 5 years ago.
#include <string>
#include <iostream>
using namespace std;
//-----------------------------------------------------------------//
//-------------------------class employee--------------------------//
//-----------------------------------------------------------------//
class Employee
{
private: string empName;
int empNum;
string hireDate;
public:
Employee():empName(""),empNum(0), hireDate("") //default ctor
{}
Employee(string name, int num, string date)
{
empName = name;
empNum = num;
hireDate = date;
}
void setempName(string n);
void setempNum(int nm);
void setHiredate(string d);
string getName();
int getNum();
string getDate();
void print();
};
void Employee::setempName(string n)
{empName = n ;}
void Employee::setempNum(int nm)
{empNum = nm;}
void Employee::setHiredate(string d)
{hireDate = d;}
string Employee::getName()
{return empName;}
int Employee::getNum()
{return empNum;}
string Employee::getDate()
{return hireDate;}
//-----------------------------------------------------------------//
//--------------------class production worker----------------------//
//-----------------------------------------------------------------//
class ProductionWorker : public Employee
{
private:
int shift;
double hrlyPay;
public:
ProductionWorker():shift(0) , hrlyPay(0.0)
{}
ProductionWorker(int sh , double pay)
{
shift = sh;
hrlyPay = pay;
}
void setshift(int s);
void setPay(double p);
int getshift();
double getPay();
void print();
};
void ProductionWorker::print()
{
cout << "Employee Name: " << getName() << endl;
cout << "Employee Number: " << getNum() << endl;
cout << "Hire Date: " << getDate() << endl;
cout << "Shift: " << getshift();
if(shift == 1)
{
cout << "(Day Shift)" << endl;}
else
cout << "(Night Shift)" << endl;
cout << "Pay Rate: $" << getPay()<< endl;
}
void ProductionWorker::setshift(int sh) //
{sh = shift;}
void ProductionWorker::setPay(double p)
{p = hrlyPay;}
int ProductionWorker::getshift()
{return shift;}
double ProductionWorker::getPay()
{return hrlyPay;}
//-----------------------------------------------------------------//
//-------------------------Main------------------------------------//
//-----------------------------------------------------------------//
int main()
{
int Shift;
double pay;
cout << "Enter 1 for Day Shift or 2 for Night Shift: "<<endl;
cout<< "Any deviation will default to Night Shift ";
cin >> Shift;
cout << "Enter hourly pay: $";
cin >> pay;
ProductionWorker emp1(Shift, pay);
emp1.setempName("Pedro, Colon");
emp1.setempNum(8675309);
emp1.setHiredate("1-1-2000");
emp1.print();
return 0;
}
When I put everything in one main function, my code works. However, when I try to separate classes into their own definition and implementation files and main in its own file. My code does not work. Is there anything wrong with my code. Please help me I'm just the beginner of c++
Problem:
I need to separate them into 1 main function, 2 definition and 2 implementation files
Your main contains using namespace std;. That makes elements of the std namespace (such as std::string) available without qualification (i.e. string).
Your header files don't contain this, so you have to qualify the type. Please don't add the using directive to the header files; doing so is considered bad style, because you force users of your header to have all the std symbols in the global namespace.
As tobi mentioned in the comments, you also should include the header files you need from where you need them, e.g. in employee.h you have a field of type std::string, so you should #include <string> in that file.

c++ bank account array, looping through

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.

Converting pounds to euros - Using Parameters

I've started a project in C++ to practice the use of parameters and I have encountered a problem in my code and I'm not quite sure why I'm getting the values I'm getting.
Here is my code:
When I run it, the values I receive from the displayFinalData output as 0 instead of the values I'm expecting (which should be whatever the conversion is etc).
#include <iostream>
using namespace std;
int main()
{
int numInEuros = 0;
char answer = 'Y';
double sumEuro = 0;
double priceEuro = 0;
int number = 0;
while ((answer == 'Y') || (answer == 'y'))
{
void processAPrice();
processAPrice();
void calculateSum(double priceInEuros, double& sumInEuros);
calculateSum(priceEuro, sumEuro);
cout << "\nDo you wish to continue? (Y/N): ";
cin >> answer;
number += 1;
}
void displayFinalData(double sumInEuros, int number);
displayFinalData(sumEuro, number);
system("pause");
return 0;
}
void processAPrice()
{
double pricePounds;
double priceEuro;
void getPriceInPounds(double& priceInPounds);
getPriceInPounds(pricePounds);
void convertPriceIntoEuros(double priceInPounds, double& priceInEuros);
convertPriceIntoEuros(pricePounds, priceEuro);
void showPriceInEuros(double priceInPounds, double priceInEuros);
showPriceInEuros(pricePounds, priceEuro);
}
void getPriceInPounds(double& priceInPounds)
{
cout << ("\nEnter price in pounds: \x9C");
cin >> priceInPounds;
}
void convertPriceIntoEuros(double priceInPounds, double& priceInEuros)
{
double conversionRate = 0.82;
priceInEuros = (priceInPounds / conversionRate);
}
void showPriceInEuros(double priceInPounds, double priceInEuros)
{
cout << ("\nThe Euro value of \x9C") << priceInPounds << " is EUR " << priceInEuros << "\n";
}
void calculateSum(double priceInEuros, double& sumInEuros)
{
sumInEuros += priceInEuros;
}
void displayFinalData(double sumInEuro, int number)
{
cout << "\nThe total sum is: EUR " << sumInEuro << "\n";
cout << "\nThe average is: EUR " << (sumInEuro / number) << "\n\n";
}
You declared priceEuros variable separately in your processAPrice() function and that gets updated after user inputs price in pounds, but the priceEuro variable in main() is untouched, and keeps incrementing your sumEuro by 0.
If you pass your priceEuros variable in main to the processAPrice() function it would work
void processAPrice(double& priceInEuros)
{
double pricePounds;
void getPriceInPounds(double& priceInPounds);
getPriceInPounds(pricePounds);
void convertPriceIntoEuros(double priceInPounds, double& priceInEuros);
convertPriceIntoEuros(pricePounds, priceInEuros);
void showPriceInEuros(double priceInPounds, double priceInEuros);
showPriceInEuros(pricePounds, priceInEuros);
}
I'm guessing you want to update the priceEuros variable? The problems is that it's a local variable. Local variables in different function have no relation, even if the have the same symbolic names.
For variables you want to share between functions you need to make them global, i.e. declare them outside the scope of any function.

Whats wrong with my class [closed]

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.
}

How to use 'fout' with inheritance

I'm taking a class in C++ and I've run into a problem. We have to create a list of bankaccounts that each have their own savings and checking account. I've come quite far, but now I have to use "ofstream& fout" to print the checking and savings of an imaginairy account.
My header file of "Account.h" looks like this (I think it's correct):
#include <iostream>
#include <cmath>
#include <fstream>
#ifndef ACCOUNT_H
#define ACCOUNT_H
using namespace std;
class Account{
protected:
string number;
double balance;
public:
Account(){}
Account(string nr, double bl);
void deposit(double am);
string get_number();
double get_balance();
double withdraw(double am);
bool equals(Account other);
virtual void print();
void println();
void println(string s);
virtual void println(ofstream& fout);
virtual void read(ifstream& fin);
};
#endif
My definition file is where it all goes horribly wrong with the fstream part:
#include "Account.h"
Account::Account(string nr, double bl){
if (bl >= 0){
number = nr;
balance = bl;
}
else{
number = "incorrect";
}
}
void Account::deposit(double am){
if (am >= 0){
balance = balance + am;
}
}
string Account::get_number(){
return number;
}
double Account::get_balance(){
return balance;
}
double Account::withdraw(double am){
if (0 <= am && am <= get_balance()){
balance = balance - am;
return am;
}
else{
return 0;
}
}
bool Account::equals(Account other){
if (number == other.get_number()){
return true;
}
return false;
}
void Account::print(){
cout << "<Account(" << number << ",";
cout << balance << ")>" ;
}
void Account::println(){
print();
cout << endl;
}
void Account::println(string s){
cout << s;
println();
}
void Account::println(ofstream& fout){
fout << number << ",";
fout << balance;
fout << endl;
}
void Account::read(ifstream& fin){
fin >> number;
}
There is something wrong with the declaration of void Account::println(ofstream& fout). It gives me the output
<Account(number,balance,0)>
instead of
<Account(number,balance)>
Why does this happen? I have many more problems with the printing of the savings and checking numbers, but i feel if I understand why this is happening I can solve those. Thank you to anyone who wants to help me.
Account::println(ofstream&) will print "", but since the balance is a double, it prints with a decimal place:
if balance == 0.0, it will be printed as eiter 0.0 or 0,0, depending on your locale.
Either way, you have way too many print methods, and I think the solution should be implemented through an output operator:
Header:
class Account {
// ....
// no print methods defined
};
std::ostream& operator <<(std::ostream& out, const Account& a);
Source:
std::ostream& operator <<(std::ostream& out, const Account& a)
{
return out << "";
}
Client code:
#include <iostream> // console
#include <fstream> // file
Account a;
// print to console
std::cout << a << std::endl;
// print to file
std::ofstream fout("./account.txt");
fout << a << std::endl;