Why does this error happen (C++)? [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a class called SavingsAccount with a method called calculateMonthlyInterest. If I arrange my main method like this, it works just fine, with saver1 having interest of $60 and saver2 having interest of $90:
void main() {
// create two savings account objects, then calculate interest for them
int balance = 200000;
SavingsAccount saver1(balance);
saver1.calculateMonthlyInterest();
balance = 300000;
SavingsAccount saver2(balance);
saver2.calculateMonthlyInterest();
cin.ignore(2); // keeps console from closing
}
However, if I arrange it like this, saver1 and saver2 both have interest of $90, even though that is incorrect for saver1:
void main() {
// create two savings account objects, then calculate interest for them
int balance = 200000;
SavingsAccount saver1(balance);
balance = 300000;
SavingsAccount saver2(balance);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
cin.ignore(2); // keeps console from closing
}
Obviously I can avoid the error by arranging it the first way, but I was just wondering why this is. Either way, shouldn't it pass a different value for the saver1 and saver2 objects, or am I missing something?
Edit: Here's the rest of the program for those who want to see it:
#include <iostream>
using namespace std;
class SavingsAccount {
public:
SavingsAccount(int& initialBalance) : savingsBalance(initialBalance) {}
// perform interest calculation
void calculateMonthlyInterest() {
/*since I am only calculating interest over one year, the time does not need to be
entered into the equation. However, it does need to be divided by 100 in order to
show the amount in dollars instead of cents. The same when showing the initial
balance */
interest = (float) savingsBalance * annualInterestRate / 100;
cout << "The annual interest of an account with $" << (float)savingsBalance / 100 << " in it is $" << interest << endl;
};
void setAnnualInterestRate(float interestRate) {annualInterestRate = interestRate;} // interest constructor
int getBalance() const {return savingsBalance;} // balance contructor
private:
static float annualInterestRate;
int& savingsBalance;
float interest;
};
float SavingsAccount::annualInterestRate = .03; // set interest to 3 percent

Think about it this way. You have a balance. Now do you want it to be the balance to every account there is? or do you want it to have different values for different accounts?
Certainly you want it to change in different accounts. That means different accounts should have different copies of the balance. What you did in the code is declaring it as a reference and passing reference through the constructor. When you accept and assign references, it does not copy the value from one to another, rather it makes both referring to the same object (balance, in this case). Now after you have intialized both, if you change the balance in main, the change will be reflected in both accounts because the savingsBalance they have and the balance inside main are essentially the same objects.
To correct it, change the int &savingsBalance to int savingsBalance, and change SavingsAccount(int& initialBalance) to SavingsAccount(int initialBalance). That will make it accept the values stored in initialBalance.

Related

I am getting garbage value while using operator overloading

I have got a question -
Write a c++ program to calculate Gross salary(net salary+DA+TDS) for 4 employees where overload the + operator for getting the total salary obtained by all the 4 employees. Also get the average salary of employees by operator overloading. display all the details of all four employees. Also display who is getting highest salary. Employee salary must be entered by the user at runtime.
#include<iostream>
#include<string>
using namespace std;
class Employee
{
private:
int net_salary, DA, TDA, Gross_salary;
public:
void SetData(int net, int da, int tda, int gross)
{
net_salary=net;
DA=da;
TDA=tda;
Gross_salary=gross;
}
void GetData()
{
cout << "Enter net salary: "<<net_salary;
DA = (15*net_salary)/100; //Declaring the value of DA as 15% and calculating the amount
//on basis of net salary of the employee
TDA = (10*net_salary)/100; //Declaring the value of TDA as 10% and calculating the amount
// of TDA on basis of net salary
Gross_salary = net_salary+DA+TDA;
}
void DisplayData()
{
cout << "Total Gross Salary = "<<Gross_salary;
}
Employee operator +(Employee e)
{
Employee temp;
temp.Gross_salary=Gross_salary+e.Gross_salary;
return temp;
}
};
int main()
{
Employee e1,e2,e3,e4,e5;
e1.GetData();
e2.GetData();
e3.GetData();
e4.GetData();
e5=e1+e2+e3+e4;
e5.DisplayData();
return 0;
}
The trouble comes from the absent initial values for the data members.
// ...
cout << "Enter net salary: " << net_salary;
DA = (15*net_salary)/100;
// ...
Here, in the GetData() member function, that is called after you have created five default initialized objects e1,e2,e3,e4,e5 of Employee type. The net_salary here is of built-in type and is default initialized by the implicitly defined default constructor, hence it has an undefined value. Then you assign this undefined value to the DA and so on in the body of the GetData().
You should not look toward the SetData() as a solution for this, since it should act as a setter method, a method used to modify an already initialized object. You will need to implement constructor(s) for your class, or you can at least supply in-class initializers for the members, like so:
// ...
int net_salary=0, DA=0, TDA=0, Gross_salary=0;
// ...
I can't help but notice that GetData() either has a confusing name or tries to do more than it is intended to do. It does some internal computation, which is ok for a GetSomething function, but it modifies internal data while does some prints.
Also, note the line (in the GetData()):
Enter net salary:
Will be followed by an output, you won't be given a chance to input any data in the GetData(). I assume, you may want to create a constructor that takes input from a user, and then call a function to do all the needed computations.

Confused between the usage of constructors and what to/what not to place in them. [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
I had basics in C, and I've just started programming in c++ two weeks ago, and find 'classes' confusing. My question is how do i put a 'cin' to input the value to determine marks, and also how do i print the grades based on the below code? I'm only printing A to F and i'm so blur right now. And for some reason if i put 'else if' instead of just 'if' the error reads as missing ; before cout. Have way too many questions, sorry about that..
#include <iostream>
using namespace std;
class StudentMark {
private:
float mark;
public:
StudentMark() //constructor
{
mark = 0.0;
cout << "Constructed an instance of class StudentMark\n";
}
void SetMark(float markofstudent)
{
mark = markofstudent;
}
void IntroduceMark()
{
if (80<mark<100)
cout << "A" << endl;
if (65<mark<79)
cout << "B" << endl;
if (50<mark<64)
cout << "C" << endl;
if (40<mark<49)
cout << "D" << endl;
if (0<mark<39)
cout << "F" << endl;
}
};
int main()
{
StudentMark FirstStudent;
FirstStudent.SetMark(89);
FirstStudent.IntroduceMark();
}
Read about "Separation of concerns" - in this case, you're defining a class StudentMark which represents instances of a course grade. Therefore the class StudentMark should only be concerned with the score itself - it should not be concerned with program input and output - because (for example) what if you wanted to reuse your StudentMark class in a platform that didn't have a text-mode console, such as a web-application or console video game? So the responsibility of using cin and cout lies elsewhere.
Similarly the constructor of your StudentMark type should be concerned only with initializing a StudentMark instance. In your case you're simply zeroing-out the score member - you don't need an explicit constructor for this.
Finally, your IntroduceMark method looks like it's concerned with converting the numerical score to a grade-letter. That's all it should do - it should not be concerned with outputting it to the user of your program. I think getGrade is a better name that is more descriptive of its purpose.
class StudentMark {
private:
float mark = 0;
public:
void setMark(float mark);
char getGrade();
}
void StudentMark::setMark(float mark) {
this->mark = mark;
}
char StudentMark::getGrade() {
if( this->mark < 39 ) return 'F';
if( this->mark < 49 ) return 'E';
if( this->mark < 59 ) return 'D';
if( this->mark < 69 ) return 'C';
// etc
}
And then used like so:
int main(int argc, char* argv[]) {
StudentMark mark;
cout << "Instantiated a StudentMark" << endl;
mark.setMark( 70 );
cout << mark.getGrade() << endl;
}
Constructors are only used as a method of creating/initializing anything that's necessary for the class to function when an object of that class is created for the first time.
They're also used as means to provide default/user-input values to the class's variables.
They should be only run once when an object of the class is instantiated.
You should think of them as the "loading" process of your class.
Constructors are especially useful when working with databases for example, for the constructor is where the connection to the database happens, which is necessary if you wanted to manipulate the database using member functions.
What to put in constructors:
In general, anything that the class requires for it's member functions to function, including variables that weren't assigned values in previous code.
What not to put in constructors:
Practically anything else that isn't required for the class to function properly.
Here's an illustration of how constructors work.
class StudentMark {
public:
//Create variable m_mark, it hasn't been assigned a value,
// therefore contains junk for a value.
float m_mark;
//The constructor is called when an object of this class is created.
//Giving mark a default value of 0.0.
StudentMark(float mark = 0.0)
{
//m_mark contained junk, now it contains the value mark.
m_mark = mark;
}
}
int main()
{
//firstMark is instantiated, it's constructor gets called.
//Since we didn't provide any user input, the default value
//which is 0.0 gets assigned to firstMark.m_mark.
StudentMark firstMark;
//Now when secondMark is instantiated, it is provided with
//the value 80, therefore m_mark gets assigned the value 80.
StudentMark secondMark(80);
}
Finally, Learncpp has very informative tutorials on classes aswell as many other aspects of the language, I strongly recommend you give them a read.

How to solve this print output in C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I had the below C++ question in the recent interview but could not do. Please help.
Given a company structure where every employee reports to a superior, all the way up to the CEO, how would you print out all the employees that a particular individual oversees?
Write a method that implements this, given the below:
// Employee object contains a string denoting the.
// employee name, and an array containing
// employees who report to this employee
Employee {
String name;
Employee[] employees;
}
I have seen and understand the recursive function. But I have not encounter such a recursive object/structure like this one.
My new question is how can an object is created and initialized from this class/structure since it is recursive?
Thank you very much again.
With the information given it is very hard to answer (and question should probably be set on hold). Anyway...
I think a recursive approach is the answer. You need a function that can take a name, search the full employee list for that name and then call the function again for every employee in the local array. Something like:
void doit(Employee& e)
{
// Print e.name
// For each employee tmp in e.employees (i.e. local array)
doit(tmp);
}
Note - this requires that there are no loops in manager-employee arrays. If there is this will be an endless loop. So this is a dangerous approach.
EDIT:
This is added due to the comment from OP.
As indicated above the question is vague and doesn't really give sufficient information to provide a good answer. The struct given in the question is not valid C++ and there is no description of how the company wide list of employees are maintained.
However to keep it simple, the printing could look like this:
struct Employee
{
void PrintAllReportingEmployee(int level)
{
cout << string(4*level, ' ') << name << endl;
level++;
for (auto& e : employeesDirectlyReportingToThisEmployee)
{
e.PrintAllReportingEmployee(level);
}
}
string name;
vector<Employee> employeesDirectlyReportingToThisEmployee;
};
// Code in some print function:
// Step 1 - find the relevant employee
Employee tmp = SomeFunctionReturningAnEmployeeBasedOnName("NameOfPerson");
// Step 2 - print all employees reporting directly and indirectly
tmp.PrintAllReportingEmployee(0);
This assumes a single top-level Employee (e.g. director) with a vector of employees directly reporting to the director. Each of these would then have a vector of employees reporting to them and so. So it is kind of an tree structure.
Note, if I should design a employee db, I would not go with such a solution.
Who ever asked the question was looking for an answer with something to do with class inheritance. So a class Persion is extended by Employee where Person is also extended by Manager etc etc where they all share some similar properties but not everything.
This means that your code can be expanded upon by other programmers and one change can fix many different classes!
Although this code does not demonstrate class inheritance, it will work.
/*
THE OUTPUT:
Jacobs-MacBook-Pro:~ jacob$ ./employee
Foo McGoo
Bar Too
Jacobs-MacBook-Pro:~ jacob$
*/
#include <iostream>
#include <string>
#include <vector>
using std::string;
using std::vector;
using std::cout;
using std::endl;
/* define class (this should be in a header file) */
class Employee{
public:
//Variables
string Name;
//Functions
Employee(const string&); //constructor
void AddCoWorker(const Employee&);
void ShowCoWorkers();
private:
vector<Employee> employees;
}; //Note the semicolon
//Entry point
int main(int argc, char **argv){
Employee foo("Foo McGoo");
Employee bar("Bar Too");
Employee me("Bevis");
me.AddCoWorker(foo);
me.AddCoWorker(bar);
me.ShowCoWorkers();
return 0;
}
//Class functions (should be in a separate cpp file)
Employee::Employee(const string& name){
this->Name = name;
}
void Employee::AddCoWorker(const Employee &e){
this->employees.push_back(e);
}
void Employee::ShowCoWorkers(){
int count = this->employees.size();
for(int i = 0; i < count; i++){
//Print the names of each co worker on separate lines
cout << this->employees[i].Name << endl;
}
}

Need to create a function for a casino game

I have a Project for my programming class, and its requiring me to set up the main functionality for the casino using functions.
First, I needed to seed the random number generator which I think I did right.
void seedRand(int seed)
{
srand(time(0));
}
Second, was to continue to set up functions. So I set the next one to print out numbers to the second decimal place.
void printMoney(double money)
{
std::cout << std::setprecision(2) << std::fixed;
}
The next one, and the one I'm not understanding, is to have the user pay, and have the casino receive the money.
Sorry if i didn't put enough information, if something is missing please ask. I'm still new to understanding everything. Any help would be appreciated. Thanks.
void payMoney(double & wallet, double amount)
{
}
which I think I did right.
No you didn't, it should rather look like
void seedRand(int seed) {
srand(seed == 0?time(0):seed);
}
If there's a parameter passed, it's probably meant to be actually used. I've chosen zero as a convention, when seed() should be called with a randomly time based value.
So I set the next one to print out numbers to the second decimal place.
Your second function sets up the output stream state well, but misses to output the value, it should look like
void printMoney(double money) {
std::cout << std::setprecision(2) << std::fixed << money << std:: endl;
// ^^^^^
}
And at least your last function is probably supposed to be implemented as
void payMoney(double & wallet, double amount) {
wallet -= amount;
}
All in all it's hard to answer what you're supposed to do with this task.
But since you tagged this question c++, I'd rather recommend to go putting these functions in context of classes like class Casino and class Player.
class Casino;
class Player {
double wallet;
public:
void payMoney(Casino& Casino, double amount);
};
class Casino {
public:
void addToBank(double money) {
bank += money;
}
private:
double bank;
};
void Player::payMoney(Casino& casino, double amount) {
wallet -= amount;
casino.addToBank(amount);
}

C++ class - Array Of objects

I've to design a ticket booking system for a cinema, which has 50 seats only (5 rows with 10 seats each)
I've been given the Cinema class below, and this should not be modified
class Cinema{
private:
Ticket ticket[50]; // not sure what it is going on
public:
Cinema(); //constructor
double purchaseTicket(int); // ticket ID as parameter, check if it is available, if so update it as unavailable. If not, return 0.
void listAll();
};
And this is the Ticket class
class Ticket{
private:
int ID[50]; //ticket ID (correct to store data in array?)
int price; // ticket price
// have to provide set and get function for ID and price, have no idea even I've googled on this topic
bool available[50]; // availability of ticket
public:
Ticket(); //constructor
bool status(int); // return availability of ticket
void setAvailable(int); //update status of ticket as available
void buy(int); //update status of ticket as unavailable
};
This is the main function (given) which simulates the purchase ticket function
int main(){
Cinema myCinema;
myCinema.listAll(); // available seats print "O", otherwise print "X"
//simulate to purchse ticket 15, 16, 17
double price = 0;
price += myCinema.purchaseTicket(15);
price += myCinema.purchaseTicket(16);
price += myCinema.purchaseTicket(17);
cout <<"\nTotal Price: $" << price << endl << endl;
//print the current status
myCinema.listAll();
return 0;
}
can anyone tell me how to use "Ticket ticket[50];" ? this troubles me a lot and many steps cannot be finished
and tell me also if there are any problems in the Ticket class
Each seat has a ticket. Therefore there are fifty tickets to purchase. It's a slightly strange way of looking at things but I think you can think of 'ticket' as synonymous with 'seat'.
Your ticket class is wrong. Remember a ticket object represents an individual ticket (which stands for an individual seat). Therefore one ticket has one id, and one availability. Therefore the arrays in the ticket class are wrong.
class Ticket{
private:
int ID; //ticket ID
int price; // ticket price
bool available; // availability of ticket
public:
...
};
The setters and getters are trivial
int Ticket::getPrice() const { return price; }
void Ticket::setPrice(int p) { price = p; }
Similar for availability.
Just noticed that Cinema::purchaseTicket returns a double, why I have no idea.
You cannot use ticket array directly, since it is a private member of Cinema. You can only access it using the purchase function mentioned in the class. Since that class should not be modified, this is the only way.
(Note: int array for ID member is wrong, use only int).
However, if you were to modify that class to make Ticket ticket[50] as public,
An example on how to use it is as follows:
myCinema.ticket[0].ID to access the first ticket's ID ( preferably use char array to store ticket ID, else just int: int array is wrong)
access the members u want through the dot operator.