C++ Vending Machine program with classes c++ - c++

I am trying to build a vending machine program with 3 different classes but I am stuck on the second portion of it. Basically the first class is the snack class, which takes 3 parameters (calories, name and price.) However, the second class VendSlot, should have two members, a snack (which I presume to be the object from the first files) and the quantity of snacks. I am really struggling to understand how to process the snack object within the second class though. How exactly do I pass the first snack object into my VendSlot class so that I can increase/decrease the amount in my storage in VendSlot and then let the user buy it when I reach the third item? I can't use pointers yet but can pass by reference and I am wondering if this is an effective way? The third class will be a vending machine that will have vendSlots and will take money to buy the items. Thank you for the help and let me know if you need clarification on the project!
This is my Snack header file
#ifndef SNACK_CPP
#include <string>
using std::string;
class Snack
{
private:
string nameOfSnack;
double snackPrice;
int numOfCalories;
public:
Snack(); //default constructor
Snack(string, double, int); //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
This is my snack.cpp file with constructors
#include "Snack.hpp"
#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;
}
Here is my VendSlot header file
#ifndef VENDSLOT_CPP
#include "Snack.h"
#include <string>
class VendSlot
{
public:
VendSlot(); //default constructor
VendSlot(string, double); //overload constructor
string getSnack(); //get snack name
int getAmount(); //get amount of snacks available
void decrementAmount(int); //function to decrease storage in vending machine by 1.
Snack snack; //passes snack object? I am confused what this should be.
~VendSlot(); //destructor
private:
double numOfSnacks; // number of snacks
};
#endif // !VENDSLOT_CPP
And here is my VendSlot.cpp file which I am struggling with
#include "VendSlot.h"
#include "Snack.h"
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
VendSlot::VendSlot()
{
snack;
numOfSnacks = 5;
}
VendSlot::VendSlot(string Snack, double Quantity)
{
snack = Snack;
numOfSnacks = Quantity;
}
int VendSlot::getAmount()
{
return numOfSnacks;
}
string VendSlot::getSnack()
{
return snack;
}
VendSlot::~VendSlot()
{
}

I'm not sure if this is the point of your program or assignment. I'm answering your question of how does the Snack class get its constructor params when it is contained within VendSlot class.
The members contained in another class get their constructor parameters from the initialization list.
Here is an example for your case of how it could be done:
Snack::Snack(string name, double price, int cals) :
nameOfSnack(name),
snackPrice(price),
numOfCalories(cals)
{
}
VendSlot::VendSlot(Snack& snack, int quantity) :
snack(snack),
numOfSnacks(quantity)
{
}
Also, note using a reference is what would normally be used when passing in an entire class or struct. This also means the default Snack copy constructor provided by the compiler will be used unless you implement one yourself. If the class only has simple native types it should work, but to be safe you should implement it yourself.
The member quantity would seem to be best be an int type as you wouldn't have fractions of a snack being sold.
Here's the assignment operator and copy constructor defined as you'll need it.
Snack& Snack::operator=(const Snack& snack)
{
this->nameOfSnack = snack.name;
this->snackPrice = snack.price;
this->numOfCalories = snack.cals;
}
Snack::Snack(const Snack& snack)
{
*this = snack;
}

When you work with classes in C++, imagine them as variables that contain variables. So use them the same way as you use variables.
When you call an instance of a class (or "declare the variables") the constructor is called. There are two ways on doing this. With or without parameters:
Snack A("Chocolate", 12.5, 199);//This will call the constructor with parameters
Snack B;//This will call the constructor without parameters
So now we have two objects of the same class. To use the memebers of the objects we just use a period.
cout << A.getNameOfSnack() << endl;//Output: Chocolate
cout << B.getNameOfSnack() << endl;//Output: bottled water
Also, keep in mind that we can access to the public members only.
Moving on, creating an instace of a class as a member of other class is not different.
class VendSlot {
public:
Snack snack;
int numOfSnacks;
VendSlot();
VendSlot(string, double);
~VendSlot();
};
VendSlot::VendSlot() {
snack = Snack();//Call the constructor to create the object
numOfSnacks = 5;
}
VendSlot::VendSlot(string nameSnack, double Quantity) {//Notice that I changed the name of the first parameter
snack = Snack(nameSnack, 0, 0);//Call the constructor to create the object
numOfSnacks = Quantity;
}
First, you need to be sure that you are not using the name of the class as the name of a variable (that will give you errors, so be careful with that). Now, since the only data you recive in the VendSlot constructor is the name of the snack, there is no more information to send as parameter to the constructor of Snack. You can either add more parameters on the VendSlot constructor or put default values.
Since the variables nameOfSnack, snackPrice and numOfCalories are private members of their class we can't change their values from outside the class Snack.
Within the class VendSlot (or where you create the instance of the class) you can only call the functions getNameOfSnack, getSnackPrice and getNumOfCalories, which are public members of Snack.
So, implying that the function VendSlot::getSnack returns the name of the snack, the function will be as following.
string VendSlot::getSnack() {
return snack.getNameOfSnack();
}
I hope this answers your question.

Related

Using a class and functions to keep track of user stats

I am new to C++, and was wondering what I am doing wrong.
I am trying to create a text-based adventure game that keeps track of player stats using an add or remove function. Currently, my function does not add five points to trust and I am trying to get it to.
#include "function.h"
using namespace std;
int main() {
double trust=100;
editPlayer user(100);
//asks user choice
cin >> firstChoice;
if (firstChoice == 1) {
user.addTrust(trust);
cout << trust;
Here is my function.cpp only using trust as an example:
#include "function.h"
editPlayer::editPlayer(double trust) {
}
void editPlayer::addTrust(double trust){
trust +=5;
}
void editPlayer::removeTrust(double trust){
trust -=5;
}
And here is my function.h:
#include<iostream>
#include<string>
using namespace std;
class editPlayer{
public:
editPlayer(double trust);
void addTrust(double);
void removeTrust(double);
};
Lets take your addTrust function:
void editPlayer::addTrust(double trust) {
trust += 5;
}
This will modify the local variable trust, and then the function will end. When the function ends, the life-time of the local variable trust also ends, and the modifications you made to it will be lost.
If you truly want to modify the argument, you need to either pass it by reference:
void editPlayer::addTrust(double& trust) {
trust += 5;
}
Or return the new value:
double editPlayer::addTrust(double trust) {
return trust + 5;
}
If you return the new value, you need to assign to it when calling the function:
trust = user.addTrust(trust);
With the above said, the code and the editPlayer class doesn't make much sense. There's just no need for a class editUser really. Possibly addTrust could be a non-member function, or maybe not a function at all.
The class name doesn't make sense, since it doesn't "edit" anything. And passing an argument to the constructor also doesn't make sense since the objects doesn't have any internal state (the value passed to the constructor is just discarded).
Currently you're not storing anything specific on behalf of user object (an object of the editPlayer class.
The cout << trust; statement just prints a value of the trust local variable which you declared at the beginning: double trust=100;. Because this variable hasn't been changed anyhow since that initialization it is still equal to 100 and this is what you see.
In order to track any editPlayer-specific information the best idea is to store that information as a data member of the class editPlayer. You can declare a data member representing the trust of an object like this:
class editPlayer{
public:
editPlayer(double trust);
void addTrust(double);
void removeTrust(double);
double getTrust() const; // add also this one, will be useful
private:
double m_trust {0}; // <---- here - a data member, aka. a class field
};
Now you must refine you constructor to let it utilize the parameter which it takes and assign its value to this new data member (because currently the constructor does nothing):
editPlayer::editPlayer(double trust) {
m_trust = trust;
}
Now in the member functions that you already have just rename the variable so that it reflects the trust data member (and not the parameter) which effectively will allow to update its value:
void editPlayer::addTrust(double trust) {
m_trust += 5;
}
void editPlayer::removeTrust(double trust) {
m_trust -= 5;
}
double editPlayer::getTrust() const { // add definition of our "getter"
return m_trust;
}
Finally you can replace that cout << trust; which we already discussed (still prints the local variable's value) with an invokation of the getter which yields m_trust's value:
cout << user.getTrust();
and see the actual effect of performing the addTrust() operation as well as get delighted with your legitimate object-oriented program.
In general the code you are asking can be covered by classes, member declarations and also a pinch of object oriented programming.
The internet has lots of good (and less than good) tutorials if you search for it.
I would try my luck with some of the following searches
CPP + classes
CPP + member declarations
CPP + dynamic vs. static memory allocation (pointers and stuff)
object oriented programming (OOP)
The examples on this site provide good (and short :D) examples of alot of basic concepts imho.
https://www.tutorialspoint.com/cplusplus/cpp_classes_objects.htm
Some of the topics also apply to other languages.
The first block with my comments:
#include "function.h"
using namespace std; // dont get into the habbit of using namespace std;
// the above can potentially open up for bugs
int main()
{
double trust=100; // This variable is declared in this scope({ ... })
// and will get deallocated once the scope ends with the character '}'
editPlayer user(100); // instance of editPlayer named 'user' is constructed
//asks user choice
cin >> firstChoice;
if (firstChoice == 1) {
user.addTrust(trust); // calling function on user object
cout << trust;
}
Now looking at the .h file i would advocate against including headers that you dont use in the header.
For small projects it does not matter at all - but for big projects of thousands lines of code removing unused includes can speed up things.
Some would prefer forward declarations - which you can look into once you are more comfortable with the basics of cpp.
#include<iostream> // not used here
#include<string> // not used
using namespace std; // disaster waiting to happen
class editPlayer{
public:
editPlayer(double trust);
void addTrust(double);
void removeTrust(double);
};
The .cpp file
#include "function.h"
editPlayer::editPlayer(double trust) {}
// function implementation with argument - but argument is not used - change to void fun(double) -> fun(void) OR fun()
void editPlayer::addTrust(double trust) { trust +=5; }
void editPlayer::removeTrust(double trust) { trust -=5; }
I did an example with class declaration and member variables.
#include <iostream>
#include <string>
// this is a class declaration
class Player
{
protected: // protected member variables
double _trust;
public: // public interface
Player(double trust);
void addTrust(double);
void removeTrust(double);
double getTrust() const;
};
// Implementation of public interface
// notice _trust is the member defined in the class
Player::Player(double trust) : _trust(trust) {} // constructor
// example of default parameters (do note that only definition or declaration can have them)
// This means that calling the function without arguments will become 5
void Player::addTrust(double trust = 5) { _trust += trust; }
void Player::removeTrust(double trust = 5) { _trust -= trust; }
double Player::getTrust() const {return _trust; }
int main()
{
Player player(100); // this will invoke the constructor - and the player object will get initialised with the given state
std::cout << player.getTrust() << std::endl;
// variable to buffer input data into - assuming type int wrt. following if
int firstChoice;
//asks user choice
std::cin >> firstChoice;
if (firstChoice == 1)
{
player.addTrust(25);
player.addTrust();
}
std::cout << player.getTrust();
}
Happy coding !

Set and get member functions manipulation of data members

So I'm an newbie to programming and I have encountered a
case for which I suppose qualifies as an authentic question
in this awesome forum. Is there a way to write statements inside my get functions so that I can obtain all the changed data member values without having to create multiple get functions
for each data member?
Regards
I am practicing building programs which are easy to maintain by localizing the effects to a class's data members by accessing and manipulating the data members through their get and set functions. In this regard I have two data members for which I wish to change. After compiling, the set functions works well by changing the values but the get functions can only return one of the data member values at a time.
class GradeBook
{
public:
void setCourseName(string code,string name)
{
CourseCode = code;
CourseName = name;
}
string getCourseName()
{
return CourseCode;
return CourseName;
}
void displayMessage()
{
cout<<"Welcome to the GradeBook for: \n" <<getCourseName()
<<endl;
}
private:
string CourseName;
string CourseCode;
};//end class GradeBook
After compiling and running the program, the program outputs the CourseCode but the CourseName doesn't get displayed. I had to create two get functions each to obtain the two data members. I don't want to have 2 get functions to obtain the data member values. I just want to use one get function to keep the code at minimum.I wish to use one get function to return two values for each data member. I have already tried using one return statement and separated the data members with a comma.
Your idea of using return twice cannot work, the first return will return control to the caller and the second will never be executed. You should have got warning about it from your compiler.
I believe that an initial solution could be to use std::pair (docs: https://en.cppreference.com/w/cpp/utility/pair), see snippet below.
NOTE: using namespace std; (which is most likely what you are doing in the code you do not show), is a bad practice, consider using the fully qualified name
#include <string>
#include <utility>
#include <iostream>
//Bad practice, I added it only to keep differences with OP code small
using namespace std;
class GradeBook
{
public:
void setCourseName(string code,string name)
{
CourseCode = code;
CourseName = name;
}
std::pair<string, string> getCourseName()
{
return {CourseCode, CourseName};
}
void displayMessage()
{
//only in C++17
auto [code, name] = getCourseName();
cout<<"Welcome to the GradeBook for: \n" << code << " - " << name
<<endl;
}
private:
string CourseName;
string CourseCode;
};//end class GradeBook
Note that auto [code, name] is a feature called structured binding, available only in C++17, if you have an older compiler, you have to return a std::pair<std::string, std::string> and access its elements using the member variables first and second.
Now, std::pair is good for this contrived example, but, for your case, you might want to consider doing something a bit more readable, because the elements of the pair have the same type so the user of your library will have difficulties remembering what is the first and second element. So you might want to use a custom-made struct with some more meaningful names.
#include <string>
#include <utility>
#include <iostream>
//Bad practice, I added it only to keep differences with OP code small
using namespace std;
struct CourseCodeAndName{
std::string code;
std::string name;
};
class GradeBook
{
public:
void setCourseName(string code,string name)
{
CourseCode = code;
CourseName = name;
}
CourseCodeAndName getCourseName()
{
return {CourseCode, CourseName};
}
void displayMessage()
{
auto codeAndName = getCourseName();
cout<<"Welcome to the GradeBook for: \n" << codeAndName.code << " - " << codeAndName.name
<<endl;
}
private:
string CourseName;
string CourseCode;
};//end class GradeBook
See this example. Alternatively you can use std::tuple.
class GradeBook
{
/* ... */
public:
std::pair<std::string, std::string> get(){
return std::make_pair(CourseName, CourseCode);
}
};
int main()
{
GradeBook book1("Hello","World")
auto result = book1.get();
cout << result.first << result.second;
}
If you write:
return x,y;
or:
return x;
return y;
You should know that in first case you get the last value (you get y), and in second case you get the value of first return (you get x, because as soon as compiler see return, function will return the value, and then function will go in epilogue state (cleaning of stack memory assigned to function, both inline and non-inline function).
And about the use of get function it's normal. If you want to use the value to do something of logic (not to display), yes you should use a lot of get function. Instead if you want to display the values, use a void function, for example "void printData();", and inside it write code to print data. You probably setted the class variables as private (following the encapsulation rules) so you will have access to them inside the print function.

Creating a class and using a constructor in C++ (assignment)

For an assignment, I have to create a movie class that contains the name of the movie, the MPAA rating, the number of people that rated it from 1 to 5, find the accumulated value for each of the ratings and the average value.
I'm mainly having trouble with the constructor and the class. I'm trying to make it take an string (And I got that part somewhat right). I'm getting a few errors on line 77 and line 83. I am also stuck since I don't know what steps I should take next. I will appreciate any help possible.
Here is what I got so far:
#include "stdafx.h"
#include <iostream>
#include <string.h>
#include <string>
// Required headers
using namespace std;
//Class movie starts
class Movie {
public:
void SetMovieName(string moviename);
// Function to set the name of the movie
// moviename = movie; later on
string GetMPAAR();
//function to return the MPAA rating
int amountofratingsof1() const;
//function to return the number of people that rated the movie as a 1
int amountofratingsof2() const;
//function to return the number of people that rated the movie as a 2
int amountofratingsof3() const;
//function to return the number of people that rated the movie as a 3
int amountofratingsof4() const;
//function to return the number of people that rated the movie as a 4
int amountofratingsof5() const;
//function to return the number of people that rated the movie as a 5
int average() const;
//function to return the average value of all ratings
std::string Movies(string moviename = "Gavecube: The Movie");
//constructor to set the movie
private:
string Movie; //variable to store the name of the movie
int peoplethatrated1; // variable to store the number of people that rated 1
int peoplethatrated2; // variable to store the number of people that rated 2
int peoplethatrated3; // variable to store the number of people that rated 3
int peoplethatrated4; // variable to store the number of people that rated 4
int peoplethatrated5; // variable to store the number of people that rated 5
};
//implementation file:
void Movie::SetMovieName(const string moviename) {
//function below checks if it is a string or not
if (!cin) {
cout << "Not a valid input. Please restart." << endl;
}
}
int Movie::amountofratingsof1()const {
}
int Movie::amountofratingsof2()const {
}
int Movie::amountofratingsof3()const {
}
int Movie::amountofratingsof4()const {
}
int Movie::amountofratingsof5()const {
}
//constructor
std::string Movie(string moviename) {
SetMovieName(moviesname)
}
int main()
{
Movie Movies("Hello");
return 0;
}
Thank you.
For constructors, they aren't like a normal function. They have no return type, not even void. Within the constructor, if you can use member initiation, you should. Here is a pretty good explanation of constructors if you go down to the Constructors section. In general it should look like:
ClassName (parameter par1, ...) : mem1(par1), ...{}
where mem1 is the data member corresponding to par1. Further down in the link is the member initiation section that covers how to do that. Once you get the constructor setup, you should finish with your member function definitions in whatever order you want then test and debug like you would any other program. Test edge cases and invalid numbers if you need to do error-checking.

How to declare a Vector object in c++?

im new to learning c++ and iam now in the stage of creating a class that contains a vector of a class object, with methods to add new objects and print them all out.
Here is my code so far:
BankAccount.h:
#ifndef BANKACCOUNT_H
#define BANKACCOUNT_H
#include <string>
using namespace std;
class BankAccount
{
public:
BankAccount(string C_Name,int C_Balance);
/*
void SetCustomerName(string C_Name);
String GetCustomerName();
void SetCustomerBalance(int C_Balance);
int GetCustomerBalance();
*/
int deposit(int deposit_);
int withdraw(int withdraw_);
private:
string customer_name;
int customer_balance = 0;
int Deposit = 0;
int Withdraw = 0;
};
#endif // BANKACCOUNT_H
BankAccount.cpp:
BankAccount::BankAccount(string C_Name,int C_Balance)
{
customer_name = C_Name;
customer_balance = C_Balance;
}
int BankAccount :: deposit(int deposit_){
Deposit = deposit_;
Deposit = Deposit + customer_balance;
cout << "\nDeposit Balance = " << Deposit;
customer_balance = Deposit;
return customer_balance;
}
int BankAccount :: withdraw(int withdraw_){
Withdraw = withdraw_;
Withdraw = customer_balance - Withdraw;
customer_balance = Withdraw;
cout<<"After Withdraw Balance is "<<customer_balance;
return customer_balance;
}
Bank.h
#ifndef BANK_H
#define BANK_H
#include <vector>
#include "BankAccount.h"
using namespace std;
class Bank
{
public:
//variables , lists
vector<BankAccount> newAccount;
BankAccount bk;
// constructor
Bank();
};
#endif // BANK_H
Bank.cpp:
#include "Bank.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
Bank :: Bank()
{
string Customer_name = " ";
int Customer_balance = 0;
cout << "Add name please ";
cin >> Customer_name ;
cout << "How much balance?";
cin >> Customer_balance;
newAccount.push_back(bk(Customer_name,Customer_balance));
}
The BankAccount class is fine, the main problem is in the Bank class.
I have created the bank class to create a vectors of BankAccount , with methods that adds all the BankAccount and print them all out.
However this error keeps appearing under the constructor of Bank.cpp:
error: no matching function for call to 'BankAccount::BankAccount()'
It seems that whenever im trying to declare the class object inside the BankAccount vector , the error keeps on occuring.Can someone please explain what am i doing wrong and how to fix this?
The problem is not having a std::vector of BankAccounts. The problem is that your Bank class has a data member defined: BankAccount bk; Since you don't have any explicit constructor arguments, it tries to use the default constructor BankAccount(). There is no constructor declared, so you get a compilation error.
I suspect that you don't actually need that bk data member and should probably just remove it.
The next issue is when you try to push_back you are calling the bk object instead of constructing an object. What you want is to just have
newAccount.push_back(BankAccount(Customer_name,Customer_balance));
If you're using C++11 or greater (which it looks like you are) you can use emplace_back instead
newAccount.emplace_back(Customer_name,Customer_balance);
This would leave your Bank Account class as follows:
class Bank {
public:
std::vector<BankAccount> newAccount;
Bank();
};
Bank::Bank() {
std::string Customer_name = " ";
int Customer_balance = 0;
std::cout << "Add name please ";
std::cin >> Customer_name ;
std::cout << "How much balance?";
std::cin >> Customer_balance;
newAccount.emplace_back(Customer_name,Customer_balance);
}
You simply forgot to implement the constructor of your BankAccount class.
BankAccount::BankAccount(string C_Name,int C_Balance)
: customer_name(C_name)
, customer_balance(C_Balance)
{
// TODO;
}
As a side note, you probably want you input parameter C_name to be a const std::string& cName (using camelCase to be coherent, so a variable should never start with a capital letter, it's only used for Classes and Structs).
Usually, we use variable_ for private members (you did the opposite).
Another tip, variables should be initialized out of the body of the constructor.
EDIT:
// This is wrong
newAccount.push_back(bk(Customer_name,Customer_balance));
It should be:
// Construct a valid BankAccount object using it's constructor to fill the vector
newAccount.push_back(BankAccount(Customer_name, Customer_balance));
The variable bk is useless and needs a default constructor BankAccount::BankAccount() hence the error.
You have not defined a default constructor. When you use push_back it will try to default construct the object then copy the one you are passing in. You also default construct the member bk in Bank. You have 2 options to fix this problem.
Define a default constructor, ie. BankAccount() {
If you are in c++11 you can use vectors emplace_back routine. You will need to redesign to remove the bk member from Bank.
All objects contained by a class are constructed before the body of the constructor. In this case, your Bank object directly contains a BankAccount object, bk, which is constructed before the opening { in your Bank constructor:
Bank :: Bank()
// ... bk is initialized here....
{
You attempt to give bk some arguments later, in the call to newAccount.push_back, but it's too late; the bk object has been initialized.
To control how objects are initialized in a constructor, you must put calls to their constructors in the initialization list:
Bank :: Bank()
: bk(Customer_name,Customer_balance)
{
... but of course you haven't yet defined Customer_name or Customer_balance.
So let's back up a bit: why are you pushing an account into your Bank when you initialize the Bank? Why would an account even exist at this point? Why does Bank have bk as a member? (Why is that one account treated specially, when there's a whole vector of accounts that are also contained by the Bank?) And how are you going to add more accounts later?
So, try this: first, default-initialize the Bank:
Bank :: Bank() {}
...or, in the header (if you're using C++11 or C++14, which you should be):
Bank(void) =default;
Then, add a method for adding accounts:
Bank::addAcount(void)
{
// ... use stdin/stdout to get `customer_name` and `customer_balance`...
newAccount.emplace_back(customer_name,customer_balance);
}
(Note that you'll need to add push_back instead of emplace_back if you're not using C++11 or C++14.)
It seems that there is no standard constructor BankAccount::BankAccount() defined in your BankAccount.h.
But when you declare the standard constructor then you run in the following error
Error 1 error LNK2019: unresolved external symbol "public: __thiscall BankAccount::BankAccount(void)" (??0BankAccount##QAE#XZ) referenced in function "public: __thiscall Bank::Bank(void)" (??0Bank##QAE#XZ) [...]
Means that the member variable Bank::bk is declared but never defined.
So to compile your code successfuly I recommend to remove the declaration of the member variable bk in the class Bank. It makes no sense. Then do the following in your Bank class.
Bank::Bank()
{
string Customer_name = " ";
int Customer_balance = 0;
cout << "Add name please ";
cin >> Customer_name;
cout << "How much balance?";
cin >> Customer_balance;
BankAccount bankAccount(Customer_name, Customer_balance);
newAccount.push_back(bankAccount);
}
You will verify successfuly that the vector newAccount get filled with a new BankAccount object.

How to write two initialization operations (one as default initialization and the other one as user inputs)? Both are class's constructors in C++

I am designing and implementing a class where I have to include two initialization operations using the class's constructors. One is the default initialization (that I think I have done properly) and the other one is the initialization from the user inputs which is supposed to be in the constructor itself(where I still have trouble to write it). I am using separate compilation, so I show the code from the file with the class and the main function from the .cpp file. I am using Dev-C++ and part of the code is below. Thanks for your help.
#include <iostream>
#include <exception>
#include <math.h>
///#include "Exception.h"
#ifndef TRIANGLE_H
#define TRIANGLE_H
using namespace std;
class Triangle
{
private:
double side1;
double side2;
double side3;
double angle_side1_side2;
double angle_side1_side3;
double angle_side2_side3;
public:
//default constructor with default initialization
Triangle::Triangle(): side1(0), side2(0), side3(0), angle_side1_side2(0), angle_side1_side3(0), angle_side2_side3(0)
{
}
//constructor with user inputs, but I know there is something wrong...
Triangle::Triangle(double s1, double s2, double s3)
{
cout<<"enter your own values:"<<endl;
cin>>s1>>s2>>s3;
side1=s1;
side2=s2;
side3=s3;
cout<<"the current lengths of sides of your triangle are: " <<endl;
}
double display_triangle_sides()
{
cout<<side1<<" "<<side2<<" "<<side3<<" ";
}
double display_triangle_Area()
{
double S=(side1+side2+side3)/2; //semiperimeter
double T=sqrt(S*(S-side1)*(S-side2)*(S-side3)); //Heron formula to calculate Area of triangle
return T;
}
};
endif
//*****************************main function below************************
#include <iostream>
#include <exception>
#include "Untitled1.h"
using namespace std;
int main()
{
Triangle tr;
cout<<" length of each side of the current triangle : ";
tr.display_triangle_sides(); //I want to show here the values entered by the users
cout<<endl<<"Here is the Area of the current triangle : " << tr.display_triangle_Area()<<endl;
cout<<"type of triangle:"<<endl;
tr.Type_of_Triangle();
system("Pause");
return 0;
}
A constructor where the user has to enter values manually is appalling design. Are you sure you have been told to do that?
The correct way to do this is something like this
class Triangle
{
Triangle::Triangle(): side1(0), side2(0), side3(0)
{
}
Triangle::Triangle(double s1, double s2, double s3) : side1(s1), side2(s2), side3(s3)
{
}
...
};
int main()
{
double s1, s2, s3;
cin >> s1 >> s2 >> s3;
Triangle t(s1, s2, s3);
...
}
In order words you enter values in the main function, and then you pass the values to the constructor.
The reason that your way of doing things is so bad is that it makes your Triangle constructor only useable in the specific context of the program you are writing now. You should design your classes so that they are reusable in different programs. This is probably a hard thing for you to appreciate now when you're just beginning, since you are focused on just getting one program to work, not thinking about programs you might write in the future.
If you really have been told that you must do this, then you are being taught by an incompetant.
You need to do like this:
int main()
{
cout<<"enter your own values"<<endl;
double s1,s2,s3;
cin>>s1>>s2>>s3;
Triangle tr(s1,s2,s3);
cout<<" length of each side of the current triangle : ";
tr.display_triangle_sides(); //I want to show here the values entered by the users
cout<<endl<<"Here is the Area of the current triangle : " << tr.display_triangle_Area()<<endl;
cout<<"type of triangle:"<<endl;
tr.Type_of_Triangle();
system("Pause");
return 0;
}
Also change consrtructor to
//constructor with user inputs, but I know there is something wrong...
Triangle::Triangle(double s1, double s2, double s3):side1(s1),side2(s2)side3(s3)
{
}
According to your task description you need an opportunity to create different configurations of the object class instances, configurartion of particular instance depends on user input.
So as one of the method to approach your task I advice your to read about programming pattern builder.
Object of class builder is responsible for creation of instances of particular class it offers such advantages as flexiable objects creation and error prevention. I wrote a small example for you:
class Triangle
{
friend class TriangleBuilder;
public:
double display_triangle_sides()
{
cout<<side1;
}
private:
double side1;
Triangle::Triangle(): side1(0){}
Triangle::Triangle(int v): side1(v){}
};
class TriangleBuilder
{
public:
void BuildDefaultTriangle(void)
{
this->m_instance = new Triangle;
}
void BuildCustomTriangle(void)
{
cout << "All right!! Enter side length)\n" << endl;
int tmp;
cin >> tmp;
this->m_instance = new Triangle(tmp);
}
Triangle* getTriangle(void)
{
return this->m_instance;
}
private:
Triangle* m_instance;
};