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

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);
};

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 ) {}

Related

C++ Object declaration needs another object as parameter

Object-oriented C++ here.
I'm supposed to code a Microwave object that "heats" a FrozenMeal object.
One method of the Microwave object, called void heatMeal(FrozenMeal), is supposed to take an instance of a FrozenMeal object as a parameter and increase its temperature.
FrozenMeal.h
#include <string>
class FrozenMeal {
public:
FrozenMeal(std::string, int);
void setTemperature(double);
std::string getName() const;
int getVolume() const;
double getCoeffizient() const;
double getTemperature() const;
private:
std::string name;
int volume;
double temperature;
double coeffizient;
};
FrozenMeal.cpp
#include <string>
#include "FrozenMeal.h"
using namespace std;
FrozenMeal::FrozenMeal(string mealName, int mealVolu) {
name = mealName;
volume = mealVolu;
temperature = -18;
coeffizient = 0.24;
}
void FrozenMeal::setTemperature(double mealTemp) { temperature = mealTemp; }
string FrozenMeal::getName() const { return name; }
int FrozenMeal::getVolume() const { return volume; }
double FrozenMeal::getCoeffizient() const { return coeffizient; }
double FrozenMeal::getTemperature() const { return temperature; }
Microwave.h
#include "FrozenMeal.h"
class Microwave {
public:
Microwave();
void morePower();
void lessPower();
void setPeriod(double);
void heatMeal(FrozenMeal); // <----------------------------
int getPower() const;
double getPeriod() const;
private:
int power;
double period;
};
Microwave.cpp
#include "Microwave.h"
using namespace std;
Microwave::Microwave() {}
void Microwave::morePower() { if (power < 1000) power += 200; }
void Microwave::lessPower() { if (power > 200) power -= 200; }
void Microwave::setPeriod(double sessionPeri) { period = sessionPeri; }
void Microwave::heatMeal(FrozenMeal mealInst) {
mealInst.setTemperature(80); //example
}
int Microwave::getPower() const { return power; }
double Microwave::getPeriod() const { return period; }
Now, my problem is that my compiler says that the file FrozenMeal.h apparently redefines the object type of FrozenMeal, even though that should be the job of the FrozenMeal.cpp file, and compiling is unsuccessful.
I tried including FrozenMeal.h to Microwave.cpp but that resulted in even more compiler errors.
I feel like I'm doing something horribly wrong here.
Add include guards to your header files so its contents doesn't get included more than once:
FrozenMeal.h:
#ifndef FROZENMEAL_H_INCLUDED
#define FROZENMEAL_H_INCLUDED
// your code ...
#endif /* FROZENMEAL_H_INCLUDED */
Microwave.h:
#ifndef MICROWAVE_H_INCLUDED
#define MICROWAVE_H_INCLUDED
// your code ...
#endif /* MICROWAVE_H_INCLUDED */
Also, you never initialize int Microwave::power and double Microwave::period so you will read and write garbage values in Microwave::morePower() and Microwave::lessPower()
As suggested in the comments, you want to take the parameter of Microwave::heatMeal() by reference so the function can modify the passed object:
void Microwave::heatMeal(FrozenMeal &mealInst)
// ^

error: base operand of '->' has non-pointer type

This is my enum header file
//use like PostionType::President
enum PositionType
{ President,
VicePresident,
Secretary,
Treasurer,
Normal
};
And in my Ballot paper header and cpp file
#include <list>
#include <iostream>
#include "Candidate.h"
#include "PositionType.h" //include enum
class BallotPaper
{
private:
PositionType _positionbp;
std::list<Candidate> _candidatesbp;
public:
BallotPaper();
void setPositionBP(PositionType positionbp);
PositionType getPositionBP();
void setCandidateBP(std::list<Candidate> candidatesbp);
std::list<Candidate> getCandidateBP();
Candidate getCandidate(int index);
void ShowCandidates();
~BallotPaper();
};
#include "BallotPaper.h"
#include <string>
#include <iostream>
void BallotPaper::setPositionBP(PositionType positionbp)
{
_positionbp = positionbp;
}
PositionType BallotPaper::getPositionBP()
{
return _positionbp;
}
void BallotPaper::setCandidateBP(std::list<Candidate> candidatesbp)
{
_candidatesbp = candidatesbp;
}
std::list<Candidate> BallotPaper::getCandidateBP()
{
return _candidatesbp;
}
void BallotPaper::ShowCandidates()
{
for(Candidate c : _candidatesbp)
{
c->IncreaseVoteCount(); //ERROR!!!!
}
}
and this will be my candidate header and cpp file
class Candidate:public Member
{
private:
int _votecount;
PositionType _position;
public:
Candidate(std::string name, int id, std::string course, int contact, std::string joindate, PositionType currentposition) ;
~Candidate();
void setVoteCount(int votecount);
int getVoteCount();
void setPosition(PositionType position);
PositionType getPosition();
void IncreaseVoteCount(); //increase _votecount
};
#include "Candidate.h"
Candidate::Candidate()
{
_votecount = 0;
}
void Candidate::setVoteCount(int votecount)
{
_votecount = votecount;
}
int Candidate::getVoteCount()
{
return _votecount;
}
void Candidate::setPosition(PositionType position)
{
_position = position;
}
PositionType Candidate::getPosition()
{
return _position;
}
void Candidate::IncreaseVoteCount()
{
_votecount++;
}
I know is a super long code, and I appreciate for your patience in looking through it. My error is that it seems that it cannot recognize the function of "IncreaseVoteCount" in 'Candidate c'.
I have try to double check the syntax and the code for multiple times but i still don't understand what is the error here.

How to pass a private member variable to another class?

Based on my Snack.cpp, Snack header file, MiniVend header file & miniVend.cpp file, I am trying to move my Snack private member - price into my MiniVend.cpp file to generate the amount * price to return a total value of items in my machine. How do I access the price from another class?
Portion of my miniVend.cpp file
double miniVend::valueOfSnacks()
{
return //// I don't know how to get snacks price in here? I need to access snacks & getSnackPrice.
}
miniVend header
#ifndef MINIVEND
#define MINIVEND
#include <string>
#include "VendSlot.h"
#include "Snack.h"
using std::string;
class miniVend
{
public:
miniVend(VendSlot, VendSlot, VendSlot, VendSlot, double); //constructor
int numEmptySlots();
double valueOfSnacks();
//void buySnack(int);
double getMoney();
~miniVend(); //desructor
private:
VendSlot vendslot1; //declare all the vending slots.
VendSlot vendslot2; //declare all the vending slots.
VendSlot vendslot3; //declare all the vending slots.
VendSlot vendslot4; //declare all the vending slots.
double moneyInMachine; //money in the machine
};
#endif // !MINIVEND
Snack.cpp
#include "Snack.h"
#include <iostream>
#include <string>
using std::endl;
using std::string;
using std::cout;
using std::cin;
Snack::Snack() //default constructor
{
nameOfSnack = "bottled water";
snackPrice = 1.75;
numOfCalories = 0;
}
Snack::Snack(string name, double price, int cals)
{
nameOfSnack = name;
snackPrice = price;
numOfCalories = cals;
}
Snack::~Snack()
{
}
string Snack::getNameOfSnack()
{
return nameOfSnack;
}
double Snack::getSnackPrice()
{
return snackPrice;
}
int Snack::getNumOfCalories()
{
return numOfCalories;
}
Snack.h file
#ifndef SNACK_CPP
#define SNACK_CPP
#include <string>
using std::string;
class Snack
{
private:
string nameOfSnack;
double snackPrice;
int numOfCalories;
public:
Snack(); //default constructor
Snack(string name, double price, int cals); //overload constructor
~Snack(); //destructor
//Accessor functions
string getNameOfSnack(); //returns name of snack
double getSnackPrice(); //returns the price of the snack
int getNumOfCalories(); //returns number of calories of snack
};
#endif // !SNACK_CPP
Assuming getSnackPrice() is public, and Snack.h does exist, you should just be able to call
snackObject.getSnackPrice() * ammount
what you need is friend keyword. Define the
friend class className;
I don't really understand why you don't just implement get()? Accessing private data is really bad. You are breaking the encapsulation. But if you really want to know (i.e. you should NOT do it, it is really BAD), then you just return a reference to a private data as shown below
#include <iostream>
class A
{
public:
A(int a) : x(a) {}
int &getPrivateDataBAD() { return x; }
void print() { std::cout << x << std::endl; }
private:
int x;
};
class B
{
public:
void print(int &s) { std::cout << s << std::endl; }
};
int main()
{
A obj(2);
B bObj;
bObj.print( obj.getPrivateDataBAD() );
return 0;
}

Member functions not getting inherited in c++

The following code has three classes. account, savings(derived), current(derived). But three of the memberfunctions from the base class are not getting inherited. This is the error what I get. Is it possible doing without using virtual functions
In file included from main.cpp:1:0:
classes.hpp:96:30: error: no ‘void savingsAccount::deposit()’ member function declared in class ‘savingsAccount’
void savingsAccount::deposit()
^
classes.hpp:105:31: error: no ‘void savingsAccount::withdraw()’ member function declared in class ‘savingsAccount’
void savingsAccount::withdraw()
^
classes.hpp:130:31: error: no ‘void savingsAccount::display()’ member function declared in class ‘savingsAccount’
void savingsAccount:: display()
^
classes.hpp:181:30: error: no ‘void currentAccount::deposit()’ member function declared in class ‘currentAccount’
void currentAccount::deposit()
^
classes.hpp:190:31: error: no ‘void currentAccount::withdraw()’ member function declared in class ‘currentAccount’
void currentAccount::withdraw()
^
classes.hpp:220:31: error: no ‘void currentAccount::display()’ member function declared in class ‘currentAccount’
void currentAccount:: display()
#include<iostream>
#include<cstring>
#define MAX 50
#ifndef classes_h
#define classes_h
using namespace std;
class account
{
protected:
char name[MAX];
int accountNumber;
char type[MAX];
float balance;
float minBalance;
static int Customers;
public:
account();
account(char*,int);
void deposit();
void withdraw();
void display();
int getAccountNumber();
static void numberOfCustomers();
};
account::account(char* name, int accountNumber)
{
strcpy(this->name,name);
this->accountNumber=accountNumber;
//strcpy(this->type,type);
this->balance=0;
Customers++;
}
int account::Customers=0;
void account ::numberOfCustomers()
{
cout<<"Total number of customer-------->"<<Customers;
}
void account::display()
{
}
/********************************
//Savings Account class
********************************/
class savingsAccount: public account
{
protected:
float minBalance;
// float rate;
public:
savingsAccount();
savingsAccount(char*,int);
savingsAccount(account&); //Copy Constructor
/* void deposit(); //user
void withdraw(); //user
void display(); //user
*/ int getAccountNumber();
};
savingsAccount::savingsAccount(char* name, int accountNumber):account(name,accountNumber)
{
minBalance=0;
strcpy(type,"savings");
}
savingsAccount::savingsAccount(account& tp):account(tp)
{
minBalance=0;
strcpy(type,"savings");
}
int savingsAccount::getAccountNumber()
{
return accountNumber;
}
void savingsAccount::deposit()
{
float amount;
cout<<"Enter the amount needs to be deposited"<<endl;
cin >> amount;
balance=balance+amount;
}
void savingsAccount::withdraw()
{
float amount ;
if(balance ==0)
{
cout<<"Account balance is Nil"<<endl;
return;
}
cout<<"Enter the amount yout would like to withdraw"<<endl;
while(1)
{
cin>>amount;
if(balance-amount<0)
{
cout<<"insufficient funds, try some less amount\n";
}
else
{
balance=balance-amount;
return ;
}
}
}
void savingsAccount:: display()
{
cout<<"Account Number"<<accountNumber<<endl;
cout<<"Name-->"<<name<<endl;
cout<<"Accounttype-->Savings"<<endl;
cout<<"Balance-->"<<balance<<endl;
cout<<"Minimum Balance -->"<<minBalance;
}
/***********************************
//Current Account class
************************************/
class currentAccount: public account
{
protected:
float minBalance;
public:
currentAccount();
currentAccount(char*,int);
currentAccount(account&);
/* void deposit();
void withdraw();
void display();
*/ int getAccountNumber();
};
/*
currentAccount::currentAccount(char* name, int accountNumber):account((char*)name,accountNumber,"current account")
{
minBalance=1000;
balance=1000;
}
*/
currentAccount::currentAccount(char* name, int accountNumber):account(name,accountNumber)
{
minBalance=0;
strcpy(type,"Current");
}
currentAccount::currentAccount(account& tp):account(tp)
{
minBalance=0;
strcpy(type,"Current");
}
void currentAccount::deposit()
{
float amount;
cout<<"Enter the amount needs to be deposited"<<endl;
cin >> amount;
balance=balance+amount;
}
void currentAccount::withdraw()
{
float amount ;
if(balance ==0)
{
cout<<"Account balance is Nil"<<endl;
return;
}
cout<<"Enter the amount yout would like to withdraw"<<endl;
while(1)
{
cin>>amount;
if(balance-amount<0)
{
cout<<"insufficient funds, try some less amount\n";
}
else
{
balance=balance-amount;
return ;
}
}
if(balance-amount<1000)
{
cout<<"Please keep the balance above minimum balance ";
}
}
void currentAccount:: display()
{
cout<<"Account Number"<<accountNumber<<endl;
cout<<"Name-->"<<name<<endl;
cout<<"Accounttype-->Current Account"<<endl;
cout<<"Balance-->"<<balance<<endl;
cout<<"Minimum Balance -->"<<minBalance;
}
int currentAccount::getAccountNumber()
{
return accountNumber;
}
#endif
When you do
void savingsAccount:: display(){/* rest here */}
you are telling the compiler to implement the definition of a member function called savingsAccount::display(). However you don't specify that you have this member function in your derived class declarations. Since you overloaded it, you need to add its signature to the derived classes, like
class savingsAccount: public account
{
/* virtual */ void display() /* override */; // probably you want this virtual in the base class
// the rest
};
otherwise the compiler only knows that there exists a base version, i.e. account::display(). So the compiler is indeed right telling you that there is no savingsAccount::display() member function, as you only have account::display(), i.e. the member function of the base class.
Your whole issue can be simplified to
struct X
{
void f();
};
struct Y: X
{
// void f();
};
// error if you don't add the signature in Y,
// there is no Y::f(), only the X::f() inherited part
void Y::f(){}
int main(){}
Live on Coliru
PS: You probably want to make those functions virtual too (and also add const to the ones that don't modify your member variables), so you have proper overriding, otherwise your derived member won't behave as you want when you have a class hierarchy controlled by a pointer-to-base.
PSS: put
#ifndef classes_h
#define classes_h
at the very beginning of your header, before any #include.

Trouble with abstract classes in c++

main:
#include <iostream>
#include <string>
#include "serviceChargeChecking.h"
int main()
{
serviceChargeChecking newAccount("Crim", 111222, 50.00, 100, 1.00);
system("PAUSE");
return 0;
}
serviceChargeChecking.h:
#ifndef H_serviceChargeChecking
#define H_serviceChargeChecking
#include "checkingaccount.h"
#include <string>
class serviceChargeChecking: public checkingAccount
{
public:
void setMonthlyFee(double);
void writeCheck(int);
void getMonthlyStatement() const;
serviceChargeChecking(std::string =" ",int = 0, double = 0.00, int= 0, double = 0.00);
private:
double serviceCharge;
};
#endif
serviceChargeChecking.cpp:
#include "serviceChargeChecking.h"
#include <iostream>
using std::string;
void serviceChargeChecking::setMonthlyFee(double fee)
{
serviceCharge=fee;
}
void serviceChargeChecking::getMonthlyStatement() const
{
checkingAccount::getMonthlyStatement();
std::cout<< "Service Charge: " << serviceCharge << std::endl;
}
void serviceChargeChecking::writeCheck(int ammount)
{
if(checkingAccount::getChecks()>0)
{
checkingAccount::setChecks(checkingAccount::getChecks()-ammount);
}
else
{
std::cout<<"No checks available." << std::endl;
}
}
serviceChargeChecking::serviceChargeChecking(string name, int acct, double bal, int numCheck, double sCharge)
{
bankAccount::setAcctOwnersName(name);
bankAccount::setAcctNum(acct);
bankAccount::setBalance(bal);
checkingAccount::setChecks(numCheck);
serviceCharge=sCharge;
}
checkingAccount.h:
#ifndef H_checkingAccount
#define H_checkingAccount
#include "bankAccount.h"
#include <iostream>
class checkingAccount: public bankAccount
{
public:
virtual void writeCheck()=0;
void deposit(double);
void withdraw(double);
void getMonthlyStatement() const;
int getChecks();
void setChecks(int);
private:
int numChecks;
};
#endif
checkingAccount.cpp:
#include "checkingAccount.h"
#include <iostream>
int checkingAccount::getChecks()
{
return numChecks;
}
void checkingAccount::setChecks(int c)
{
numChecks=c;
}
void checkingAccount::deposit(double d)
{
bankAccount::setBalance(bankAccount::getBalance()+d);
}
void checkingAccount::withdraw(double w)
{
bankAccount::setBalance(bankAccount::getBalance()-w);
}
void checkingAccount::getMonthlyStatement() const
{
bankAccount::getMonthlyStatement();
}
bankAccount.h:
#ifndef H_bankAccount
#define H_bankAccount
#include <string>
class bankAccount
{
public:
std::string getAcctOwnersName() const;
int getAcctNum() const;
double getBalance() const;
void getMonthlyStatement() const;
void setAcctOwnersName(std::string);
void setAcctNum(int);
void setBalance(double);
virtual void withdraw(double)=0;
virtual void deposit(double)=0;
private:
std::string acctOwnersName;
int acctNum;
double acctBalance;
};
#endif
bankAccount.cpp:
#include "bankAccount.h"
#include <iostream>
using std::string;
string bankAccount::getAcctOwnersName() const
{
return acctOwnersName;
}
int bankAccount::getAcctNum() const
{
return acctNum;
}
double bankAccount::getBalance() const
{
return acctBalance;
}
void bankAccount::setAcctOwnersName(string name)
{
acctOwnersName=name;
}
void bankAccount::setAcctNum(int num)
{
acctNum=num;
}
void bankAccount::setBalance(double b)
{
acctBalance=b;
}
void bankAccount::getMonthlyStatement() const
{
std::cout << "Name on Account: " << getAcctOwnersName() << std::endl;
std::cout << "Account Id: " << getAcctNum() << std::endl;
std::cout << "Balance: " << getBalance() << std::endl;
}
I know this is a lot of code to go through but can anyone help me understand why i cannot create an object from the class serviceChargeChecking the error is telling me that i cannot create an object from the abstract class but it doesn't seem to be abstract to me.
serviceChargeChecking implements void writeCheck(int), but the pure virtual function from checkingAccount has type void writeCheck(), so it's still pure in serviceChargeChecking, which makes the class abstract.
You have this in the abstract class checkingAccount:
virtual void writeCheck()=0;
but implement this in the derived class serviceChargeChecking:
void writeCheck(int);
The signature must be the same.
The writeCheck() method has different signatures in serviceChargeChecking and checkingAccount.
If you use C++11, use override in order to avoid this kind of error.
It's because your CheckingAcount has writeCheck() and serviceChargeChecking has writeCheck(int);
This probably due to the fact that you failed to Override checkingAccount's, writeCheck method, the abstract prototype was was
in checkingAccount class
virtual void writeCheck()=0;
and in serviceChargeChecking class
void writeCheck(int);
note the parameters, you didn't override checkingAccount's writeCheck you probably inherited it (implicitly), the serviceChargeChecking made a new writeCheck with an int parameter.