Can I print object name in calss member function c++?
For example, I create an account1 object of the Account class in main, and I want to print the balance(member variable of Account class) like this.
class Account{
private:
int balance;
public:
void setBalance(){
//"Enter" << object_name << "'s balance : ";
cin >> balance;
}
void showBalance(){
//object_name << "'s balance : ";
cout << balance << endl;
}
};
int main()
{
Account account1;
account1.setBalance();
account1.showBalance();
}
Enter account1's balance : 50
account1's balance : 50
How Can I do?
class Account {
public:
int accountNumber;
float accountBalance;
Account() {
accountNumber = 0;
accountBalance = 0.0;
}
};
int main() {
Account user; //make a Account object
user.accountNumber = 14538; //assign
user.accountBalance = 100.55; //You can also use cin......for user user input
cout << "Amigo has $" << user.accountBalance << ". balance valaa...!\n";
return 0;
}
Related
I'm trying to write a C++ code for a course I'm enrolled in, where I keep the information of the students enrolled in the course.
I should be able to add a student to the classrrom in the user interface written in main , by calling the function void addNewStudent(int ID, string name, string surname), where I create my object instances, Student, and Course inside the function.
I should also be able to search by given ID by calling the function void showStudent(int ID) in the main, where the function uses the getStudent(ID) method of the object of the classCourse
I did not write all the methods, but when I try to debug this code, I got the error " Exception has occured, unknown signal error."
My questions are:
What is the reason of this error? How can I fix it?
Suppose that the user interface in the main is necessary to use as well as the functions it calls. Do I have to create a class object again inside each function as I wrote?
Can a more effective implementation be made in accordance with the object oriented principles I have defined above?
#include <iostream>
using namespace std;
#define MAX 10
class Student {
private:
int ID;
string name;
string surname;
public:
Student()
{
ID = 0;
string name = "" ;
string surname = "";
}
void setID(int ID_set);
int getID();
void setName(string name_set);
string getName();
void setSurName(string surname_set);
string getSurName();
};
class Course {
private:
Student students[MAX];
int num =0 ; // The current number of students in the course, initially 0.
float weightQ;
float weightHW;
float weightF;
public:
Course()
{
students[num] = {};
weightQ = 0.3;
weightHW = 0.3;
weightF = 0.4;
}
int getNum(); // Returns how many students are in the course
void addNewStudent(Student new_student);
void updateWeights(float weightQ_update, float weightHW_update, float weightF_update);
void getStudent(int ID_given);
};
// Method declerations for the class Student
void Student :: setID(int ID_set){
ID = ID_set;
}
int Student :: getID(){
return ID;
}
void Student :: setName(string name_set){
name = name_set;
}
string Student :: getName(){
return name;
}
void Student :: setSurName(string surname_set){
surname = surname_set;
}
string Student :: getSurName(){
return surname;
}
// Method declerations for the class Course
int Course :: getNum(){
return num;
}
void Course :: addNewStudent(Student new_student){
students[num] = new_student ;
num = num + 1;
}
void Course :: updateWeights(float weightQ_update, float weightHW_update, float weightF_update){
weightQ = weightQ_update;
weightHW = weightHW_update;
weightF = weightF_update;
}
void Course :: getStudent(int ID_given){
for(int i = 0; i<MAX; i++){
if(ID_given == students[i].getID()){
cout << "Student Name & Surname : " << students[i].getName() << " " << students[i].getSurName()<<"\n";
}
}
}
void addNewStudent(int ID, string name, string surname){
Student student;
Course ECE101;
student.setID(ID);
student.setName(name);
student.setSurName(surname);
ECE101.addNewStudent(student);
}
void showStudent(int ID){
Course ECE101;
ECE101.getStudent(ID);
}
int main(){
Course ECE101;
cout << "Welcome to the ECE101 Classroom Interface"<<"\n";
cout << "Choose your option\n";
string option_1 = "1) Add a student ";
string option_2 = "2) Search a student by ID";
cout << "Enter your option: ";
int x;
int ID;
string name, surname;
cin >> x;
if (x == 1)
cout << "Enter the student ID ";
cin >> ID;
cout << endl;
cout << "Enter the student name ";
cin >> name;
cout << endl;
cout << "Enter the student surname " ;
cin >> surname;
addNewStudent(ID, name, surname);
return 0;
}
To make the menu more interactive you could add a do while statement that would accept 3 options:
register
show data
exit
int main(){
Course ECE101;
int x;
int ID;
string name, surname;
string option_1 = "1) Add a student\n";
string option_2 = "2) Search a student by ID\n";
cout << "Welcome to the ECE101 Classroom Interface\n";
cout << "Choose your option\n";
cout << option_1 << option_2;
cin >> x;
do {
if (x == 1) {
cout << "Enter the student ID ";
cin >> ID;
cout << endl;
cout << "Enter the student name ";
cin >> name;
cout << endl;
cout << "Enter the student surname " ;
cin >> surname;
addNewStudent(ID, name, surname, ECE101);
}
else {
cout << "Enter the student ID\n";
cin >> ID;
showStudent(ID, ECE101);
}
cout << "Choose your option\n";
cin >> x;
} while(x != 3);
return 0;
}
addnewStudent() and showStudent() methods now accepts an instance of Course as an argument to be able to add students.
void addNewStudent(int ID, string name, string surname, Course &course) {
Student student;
student.setID(ID);
student.setName(name);
student.setSurName(surname);
course.addNewStudent(student);
}
void showStudent(int ID, Course &course) {
course.getStudent(ID, course);
}
the function is modified from the same class as well.
void Course::getStudent(int ID_given, Course &course) {
for(int i = 0; i<MAX; i++){
if(ID_given == students[i].getID()){
cout << "Student Name & Surname : " << students[i].getName() << " " << students[i].getSurName()<<"\n";
}
}
}
Demo
Your addNewStudent function creates a new course everytime it is called. You could pass a reference to the course as a parameter into the function and call Course.addNewStudent(student). You'll want to make sure you specify it's a reference though when you define your function or you'll just create a copy of the course.
#include <iostream>
#include <cstring>
using namespace std;
class Film {
private:
string name;
int year_prod;
string producer;
string main_actor;
public:
Film();
void print()
{
cout << "\nThe name of movie: " << name;
cout << "\nThe year of produced: " << year_prod;
cout << "\nProducer: " << producer;
cout << "\nMain actor: " << main_actor << endl;
}
void SetName(string xName)
{
name = xName;
}
string GetName()
{
return name;
}
void SetYearP(int xYearP)
{
year_prod = xYearP;
}
int GetYearP()
{
return year_prod;
}
void SetProducer(string xProducer)
{
producer = xProducer;
}
string GetProducer()
{
return producer;
}
void SetMaina(string xMaina)
{
main_actor = xMaina;
}
string GetMaina()
{
return main_actor;
}
};
int main()
{
Film obs[100]; // maximum of 100 hundred films
int n;
cout << "how many films ";
cin >> n;
for (int i = 0; i < n; ++i)
{
string name;
int year;
string prod;
string actor;
cout << "enter the film name ";
cin >> name;
cout << "enter the production year ";
cin >> year;
cout << "enter the producer name ";
cin >> prod;
cout << "enter the actor name ";
cin >> actor;
obs[i].SetName(name);
obs[i].SetYearP(year);
obs[i].SetProducer(prod);
obs[i].SetMaina(actor);
}
}
I've done half of my code but I get errors while compiling saying: unresolved external symbol "public: __thiscall Film::Film(void)" (??0Film##QAE#XZ) referenced in function _main AND 1 unresolved externals. I'm not sure if I had in the correct way objects of n Film from user input because I'm still a beginner in OOP.
You didn't implement your constructor:
public:
Film();//<-- declared, but not defined.
If you don't want your constructor to do anything, just add an empty body:
public:
Film() {};
or even better, explicitly declare it as the default-constructor:
public:
Film()=default;
Please try this out. Hope this helps.
class Film {
...
...
...
public:
//Film(); Remove this line if you are not defining Film()
void print()
{
cout << "\nThe name of movie: " << name;
cout << "\nThe year of produced: " << year_prod;
cout << "\nProducer: " << producer;
cout << "\nMain actor: " << main_actor << endl;
}
...
...
...
}
If you want it to be a default constructor add an empty block Film(){}
You have to implement the constructor for your class. The constructor is the method that create an instance of the class. The set functions have the purpose to modify the attributes of an object, but the initialization of the attributes must be done in the constructor.
For example:
public:
//default constructor: it does not take
//anything as input, it sets name as an
//empty string and the year to 1900
Film(){
name = "";
year = 1900;
}
// It creates a Film object, whose name
// is NAME and whose year is YEAR
Film(string NAME, int YEAR){
name = NAME;
year = YEAR;
}
// set function which allows to modify the
// year of a Film object.
void setYear(int newYear){
year = newYear;
}
Have a look here for a quick introduction.
EDIT: you may want to set the default constructor as
Film(){};
In this way you have to invoke all the set functions to initialise its attributes.
I'm not really sure if the title is correct but i have the following piece of code:
#include <iostream>
#include <string>
using namespace std;
class department
{
private:
string name;
int budget;
public:
int NoT; //Number of teachers
int NoS; //Number of students
void setName(string nam);
void setBudget(int budg);
int getBudget ();
string getName();
};
class school
{
private:
int YoE;
string name;
public:
department *dpt;
int NoDpts;
school();
};
void department::setName(string nam)
{
name=nam;
}
void department::setBudget(int budg)
{
budget=budg;
}
int department::getBudget()
{
return budget;
}
string department::getName()
{
return name;
}
school::school()
{
YoE=2000; // Year of estabilishment
name="Somename";
NoDpts=37;
}
int main()
{
string name;
int budget;
int budg;
school *sch;
sch=new school;
if (!sch)
throw("Out of memory");
sch->dpt=new department[37];
if (!sch->dpt)
throw("Out of memory");
for (int i=0;i<sch->NoDpts;i++)
{
cout << "Insert name for department#" << i+1 << ": ";
cin >> name;
sch->dpt->setName(name);
cout << "Insert budget for department " << name << ": ";
cin >> budget;
sch->dpt->setBudget(budget);
cin.ignore();
}
cout << "Insert a budget for school: ";
cin >> budget;
for (int i=0;i<sch->NoDpts;i++)
{
if (budg=sch->dpt->getBudget()>=budget)
{
cout << "Name of department is: " << sch->dpt->getName() << endl;
cout << "Budget of department amounts to: " << sch->dpt->getBudget() << endl;
cout << endl;
}
}
return 0;
}
As you can see, i allocated 37 departments, however i don't know how to access them.I mean that in the following line:
sch->dpt->setName(name);
I merely access the name of the first department (indirectly by using an accessor function),thus overwriting it and getting different results than expected.This happens to other members too such as
sch->dpt->setBudget(budget);
So i am simply asking how i can access the members of the rest of the departments.
This is my class function
class Employee
{
private:
string ename;
double esalary;
public:
Employee(string nm = "", double sal = 0.0)
{
ename = nm;
esalary = sal;
}
string getName()
{ return ename;}
double getSalary()
{ return esalary;}
};
#endif
and now my incomplete body...
#include "employee.h"
using namespace std;
Employee read_employee()
{
string name;
cout << "Please enter the name: ";
getline(cin, name);
double salary;
cout << "Please enter the salary: ";
cin >> salary;
Employee r(name, salary);
return r;
}
int main()
{
Employee emp(string name,double salary);
read_employee();
}
I am wondering how do i call the "getName or getSalary" functions from the class. I am used to the class objects without parameters.
Try this:
Employee emp = read_employee();
Instead of:
Employee emp(string name,double salary);
read_employee();
And then you can say:
emp.getName() and emp.getSalary()
Your problem is that your read_employee() function is a global function. That is, it's not necessarily attached to any specific Employee instance. If you added it to your Employee class, things might work a little better:
class Employee
{
private:
string ename;
double esalary;
public:
Employee(string nm = "", double sal = 0.0)
{
ename = nm;
esalary = sal;
}
string getName()
{ return ename;}
double getSalary()
{ return esalary;}
void read_employee()
{
cout << "Please enter the name: ";
getline(cin, ename);
cout << "Please enter the salary: ";
cin >> esalary;
}
};
And then in main:
#include "employee.h"
using namespace std;
int main()
{
Employee emp;
emp.read_employee();
cout << emp.getName() << endl;
cout << emp.getSalary() << endl;
}
Disclaimer: I'm not doing any error checking at all, so we just have to assume the user will play nice with his/her inputs.
As Chris mentions, you are not assigning the return values of your functions to anything. You want something like:
Employee emp = read_employee("Johnny", 45000);
Which will create an employee object in your function, then return it. That returned object is then assigned to emp.
Ive been up for a while coding and it is probably an easy mistake that im just overlooking from lack of sleep, but the problem happens with this segment of code.
do
{
aWithIntAcct.enterAccountData();
aWithIntAcct.getSavInfo();
aWithIntAcct.getCheckingInfo();
checkAcct.push_back(aWithIntAcct);
cout << "Would you like to enter another Checking Account with interest? y or n ";
cin >> quitChar;
}while(quitChar != QUIT);
it says that I have ambiguous access of 'enterAccountData' (Error C2385)
This is contradictory to the other (Error C3861) identifier not found.
My Classes are inherited so im not sure why this inst working for me. Any suggestions?
REST OF CODE:
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
template <class T>
void repeatValue(T val, int times)
{
for(int x = 0; x < times; x++)
{
cout << "-";
}
};
template <class T>
void produceReport(int tableRows, string title, T acctType)
{
cout << tableRows << endl;
cout << title << endl;
cout << acctType;
};
class BankAccount
{
friend ostream& operator<<(ostream&, const BankAccount&);
friend istream& operator>>(istream&, BankAccount&);
private:
int acctNum;
double acctBal;
public:
BankAccount(int = 0,double = 0.0);
double operator+=(BankAccount);
int operator+(BankAccount);
friend bool operator>(BankAccount &acctBalOne, BankAccount &acctBalTwo);
friend bool operator<(BankAccount &acctBalOne, BankAccount &acctBalTwo);
int operator==(const BankAccount acctNumOne);
void enterAccountData();
void displayAccount();
void setAcctNum(int);
void setAcctBal(double);
int getAcctNum();
double getAcctBal();
};
BankAccount::BankAccount(int num, double bal)
{
acctNum = num;
acctBal = bal;
}
double BankAccount::operator+=(BankAccount bankAcct)
{
acctBal += acctBal + bankAcct.acctBal;
return acctBal;
}
int BankAccount::operator+(BankAccount newAcctNum)
{
const int INCREMENT = 1;
newAcctNum.acctNum = acctNum + INCREMENT;
return newAcctNum.acctNum;
}
bool operator>(BankAccount &acctBalOne, BankAccount &acctBalTwo)
{
return acctBalOne.acctBal > acctBalTwo.acctBal;
}
bool operator<(BankAccount &acctBalOne, BankAccount &acctBalTwo)
{
return acctBalOne.acctBal < acctBalTwo.acctBal;
}
int BankAccount::operator== (const BankAccount acctNumOne)
{
int truth = 0;
if(acctNum == acctNumOne.acctNum)
truth = 1;
return truth;
}
ostream& operator<<(ostream& display, const BankAccount& aAcct)
{
display << "Account #" << aAcct.acctNum << endl;
display << "Account Balance $" << aAcct.acctBal << endl;
return display;
}
istream& operator>>(istream& dataIn, BankAccount& aAcct)
{
cout << endl << "Enter in an Account # ";
dataIn >> aAcct.acctNum;
cout << "Enter in an Account Balance $ ";
dataIn >> aAcct.acctBal;
return dataIn;
}
void BankAccount::enterAccountData()
{
cout << "Enter the Account:#";
cin >> acctNum;
cout << endl << "Enter the Account Balance:$";
cin >> acctBal;
}
void BankAccount::displayAccount()
{
cout << "The Account number is #" << acctNum << endl;
cout << "The Account Balance is $" << acctBal << endl;
}
void BankAccount::setAcctNum(int num)
{
acctNum = num;
}
void BankAccount::setAcctBal(double bal)
{
acctBal = bal;
}
int BankAccount::getAcctNum()
{
return acctNum;
}
double BankAccount::getAcctBal()
{
return acctBal;
}
class SavingsAccount : public BankAccount
{
friend ostream& operator<<(ostream&, const SavingsAccount&);
private:
double interest;
public:
SavingsAccount(double = 0.0);
void displaySavAccount();
void getSavInfo();
};
SavingsAccount::SavingsAccount(double intRate)
{
interest = intRate;
}
void SavingsAccount::getSavInfo()
{
cout << "Enter Interest Rate: ";
cin >> interest;
}
ostream& operator<<(ostream& display, SavingsAccount& aSavAcct)
{
aSavAcct.displaySavAccount();
return display;
}
void SavingsAccount::displaySavAccount()
{
cout << " Savings information. " << endl;
cout << "Interest Rate on the account is:" << interest << endl;
}
class CheckingAccount : public BankAccount
{
friend ostream& operator<<(ostream& display, const CheckingAccount& aCheckAcct);
private:
double monthlyFee;
int checksAllowed;
public:
CheckingAccount(double = 0,int = 0,int = 0,double = 0);
void displayCheckAccount();
void getCheckingInfo();
};
CheckingAccount::CheckingAccount(double fee, int allowed, int num, double bal) : BankAccount(num,bal), monthlyFee(fee), checksAllowed(allowed)
{
}
void CheckingAccount::getCheckingInfo()
{
cout << "Enter monthly fee of the Account for the checking account. $";
cin >> monthlyFee;
cout << endl << "How many checks are allowed?" << endl;
cin >> checksAllowed;
}
ostream& operator<<(ostream& display, CheckingAccount& aCheckAcct)
{
aCheckAcct.displayCheckAccount();
return display;
}
void CheckingAccount::displayCheckAccount()
{
cout << " Checking Information " << endl;
BankAccount::displayAccount();
cout << "Monthly fee on the account is:$" << monthlyFee << endl;
cout << "Checks allowed for this account is: " << checksAllowed << endl;
}
class CheckingWithInterest : public SavingsAccount, public CheckingAccount
{
private:
public:
CheckingWithInterest();
void displayWithInterest();
};
CheckingWithInterest::CheckingWithInterest() : CheckingAccount(0,0,9999,0), SavingsAccount(0.03)
{}
void CheckingWithInterest::displayWithInterest()
{
CheckingAccount::displayCheckAccount();
SavingsAccount::displaySavAccount();
}
int main()
{
cout << fixed << setprecision(2);
unsigned count;
vector<SavingsAccount>savAcct;
SavingsAccount aSavAcct;
vector<CheckingAccount>checkAcct;
CheckingAccount aCheckAcct;
vector<CheckingWithInterest>withIntAcct;
CheckingWithInterest aWithIntAcct;
const char QUIT = 'n';
char quitChar = 'y';
cout << "Do you want to enter Savings Information? y or n ";
cin >> quitChar;
do
{
aSavAcct.enterAccountData();
aSavAcct.getSavInfo();
savAcct.push_back(aSavAcct);
cout << "Would you like to enter another Savings Account? y or n ";
cin >> quitChar;
}while(quitChar != QUIT);
cout << "Do you want to enter Checking Information? y or n ";
cin >> quitChar;
do
{
aCheckAcct.enterAccountData();
aCheckAcct.getCheckingInfo();
checkAcct.push_back(aCheckAcct);
cout << "Would you like to enter another Checking Account? y or n ";
cin >> quitChar;
}while(quitChar != QUIT);
cout << "Do you want to enter Checking with interest account Information? y or n ";
cin >> quitChar;
do
{
aWithIntAcct.enterAccountData(); // error points here for both (Line 233)
aWithIntAcct.getSavInfo();
aWithIntAcct.getCheckingInfo();
checkAcct.push_back(aWithIntAcct);
cout << "Would you like to enter another Checking Account with interest? y or n ";
cin >> quitChar;
}while(quitChar != QUIT);
sort(savAcct.begin(), savAcct.end());
for(count = 0; count < savAcct.size(); ++count)
{
repeatValue(savAcct.at(count), count);
cout << endl;
produceReport(savAcct.size(), "Savings Account Information", savAcct.at(count));
}
sort(checkAcct.begin(), checkAcct.end());
for(count = 0; count < checkAcct.size(); ++count)
{
repeatValue(checkAcct.at(count), count);
cout << endl;
produceReport(checkAcct.size(), "Checking Account Information", checkAcct.at(count));
}
sort(withIntAcct.begin(), withIntAcct.end());
for(count = 0; count < withIntAcct.size(); ++count)
{
repeatValue(withIntAcct.at(count), count);
cout << endl;
produceReport(withIntAcct.size(), "Checking with interest Account Information", withIntAcct.at(count));
}
system("pause");
return 0;
}
class BankAccount
class SavingsAccount : public BankAccount
class CheckingAccount : public BankAccount
class CheckingWithInterest : public SavingsAccount, public CheckingAccount
This inheritance hierarchy is (probably) incorrect. Right now it looks like this:
BankAccount BankAccount
| |
SavingsAccount CheckingAccount
\ /
CheckingWithInterest
So, each CheckingWithInterest object actually has two BankAccount base class subobjects: one from its SavingsAccount base class subobject and one from its CheckingAccount base class subobject.
So, when you try to call a BankAccount member function on a CheckingWithInterest object, e.g.,
CheckingWithInterest account;
account.enterAccountData();
the compiler doesn't know whether you mean the enterAccountData() from the BankAccount that is part of the SavingsAccount base class or you mean the enterAccountData() from the BankAccount that is part of the CheckingAccount base class.
I'm not sure what, exactly, your requirements are, but if you only want to have a single BankAccount base class subobject, you probably need to use virtual inheritance when you derive CheckingAccount and SavingsAccount from BankAccount, so that the BankAccount subobject is shared between them when they are composed in CheckingWithInterest:
class BankAccount
class SavingsAccount : public virtual BankAccount
class CheckingAccount : public virtual BankAccount
class CheckingWithInterest : public SavingsAccount, public CheckingAccount
If you really do want there to be two BankAccount base class subobjects, then when you call enterAccountData(), you need to qualify on which base class subobject you want to call the member function:
account.CheckingAccount::enterAccountData();