Class Employee ID count c++ [duplicate] - c++

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 4 years ago.
I'm editing it, now ok i apply an empty constructor and my code worked but this way:
Name1 SName1 1000 0.2 100
Name2 SName2 1000 0.3 750
This code normally works perfectly and my teacher especially wants us to use "this->" and "*this" so here's my code:
my .h file
#ifndef COMEMPLOYEE_H
#define COMEMPLOYEE_H
#include <string>
using namespace std;
class ComEmployee
{
protected:
string firstName;
string lastName;
static int ID;
double grossSale;
double comRate;
public:
ComEmployee();
ComEmployee(string, string, double, double);
ComEmployee& setfirstName(string);
ComEmployee& setlastName(string);
ComEmployee& setgrossSale(double);
ComEmployee& setcomRate(double);
string getfirstName();
string getlastName();
double getgrossSale();
double getcomRate();
int getID() const;
double calCom() const;
void Display() const;
};
#endif
my .cpp file
#include "ComEmployee.h"
#include <iostream>
using namespace std;
int ComEmployee::ID = 1000;
ComEmployee::ComEmployee(){}
ComEmployee::ComEmployee(string name, string lname, double gs, double comr)
{
this->firstName = name;
this->lastName = lname;
this->grossSale = gs;
this->comRate = comr;
++ID;
}
int ComEmployee::getID() const
{
return ID;
}
ComEmployee & ComEmployee::setfirstName(string name)
{
firstName = name;
return *this;
}
ComEmployee & ComEmployee::setlastName(string lname)
{
lastName = lname;
return *this;
}
ComEmployee & ComEmployee::setgrossSale(double gs)
{
grossSale = gs;
return *this;
}
ComEmployee & ComEmployee::setcomRate(double comr)
{
comRate = comr;
return *this;
}
string ComEmployee::getfirstName()
{
return firstName;
}
string ComEmployee::getlastName()
{
return lastName;
}
double ComEmployee::getgrossSale()
{
return grossSale;
}
double ComEmployee::getcomRate()
{
return comRate;
}
double ComEmployee::calCom() const
{
return grossSale*comRate;
}
void ComEmployee::Display() const
{
cout << firstName << " " << " " << getID() << " " << comRate << " " << calCom() << endl;
}
here's my main.cpp file
#include <iostream>
#include "ComEmployee.h"
using namespace std;
int main()
{
ComEmployee employee, employee2;
employee.setfirstName("Name1").setlastName("SName1").setgrossSale(500).setcomRate(0.2).Display();
employee2.setfirstName("Name2").setlastName("SName2").setgrossSale(2500).setcomRate(0.3).Display();
system("pause");
}
I want my output as:
Name1 SName1 1001...
Name2 SName2 1002...

You have to change your design a bit. As ID is employee ID, it cannot be a static variable. A static variable belongs to the class rather than to particular instance of
the class.
Define ID as a normal member of the class.
You can use a new static variable CurrentID instead to keep track of the employees.
After defining it like below,
int ComEmployee::CurrentID = 1000;
In the default and non-default constructors, do the following:
this->ID = CurrentID++;

Add some int variable to your class definition:
int m_ID;
Then, you need to emplement a default constructor in cpp-file:
// cpp
ComEmployee::ComEmployee()
{
m_ID = ID++;
}
And modify your GetID function:
int ComEmployee::GetID() const
{
return m_ID;
}

Related

Fuction-definition not allowed RetailItem

I got some problem when run my coding. I got 2 separate file to create RetailItem class and create main. I create both in project.
Below are main.cpp
//main
#include "retailitem.h"
#include <iostream>
#include <iomanip>
using namespace std;
using std::cout;
void displayItem(RetailItem *, const int);
int main()
{
const int Item = 3;
RetailItem ritem[Item] ={ { "Jacket", 12, 59.95 },
{ "Designer Jeans", 40, 34.95 },
{ "Shirt", 20, 24.95 } };
//cout << fixed << setprecision(2);
void displayItem(RetailItem *ritem, const int Item){
cout <<" DESCRIPTION UNITS ON HAND PRICE";
cout<<"=================================================================\n";
for (int i = 0; i < Item; i++)
{
cout << setw(12) << ritem[i].getDesc();
cout << setw(12) << ritem[i].getUnits();
cout << setw(8) << ritem[i].getPrice();
}
cout << "===================================================================";
}
return 0;
}
and there one more file retailitem.h
//RetailItem class
#include <string>
using namespace std;
class RetailItem
{
private:
string description;
int unitsOnHand;
double price;
public:
RetailItem(string,int,double);
void setDesc(string d);
void setUnits(int u);
void setPrice(double p);
string getDesc();
int getUnits();
double getPrice();
};
RetailItem::RetailItem(string desc, int units, double cost)
{
description = desc;
unitsOnHand = units;
price = cost;
}
void RetailItem::setDesc(string d)
{
description = d;
}
void RetailItem::setUnits(int u)
{
unitsOnHand = u;
}
void RetailItem::setPrice(double p)
{
price = p;
}
string RetailItem::getDesc()
{
return description;
}
int RetailItem::getUnits()
{
return unitsOnHand;
}
double RetailItem::getPrice()
{
return price;
}
when compile and run main,
[Error] a function-definition is not allowed here before '{' token
[Error] expected '}' at end of input
I don't know what to fix, how can I solve it?
The error message undoubtedly contained a line number that told you where the problem was. That's an important part of describing the problem. But here it happens to be obvious: void displayItem(RetailItem *ritem, const int Item){ is the start of a function definition. You can't define a function inside another function. Move this outside of main.

Passing an object as argument in c++

Iam new to c++ trying to learn about namespaces and class.
I have 2 classes here Both are in different files.
The first one is
#include<iostream>
using namespace std;
namespace project{
class Student{
string name,address,enrolmentDate ,usn;
int hours;
public:
Student(char* nusn, char* nname, char* naddress, char* ndate,int nhours){
usn = nusn;
name = nname;
address = naddress;
enrolmentDate = ndate;
hours = nhours;
}
Student(){
getData();
}
void getData(){
std::cout << "Enter Usn,Name,Address,EnrolmentDate,Hours\n";
std::cin >> usn >> name >> address >> enrolmentDate >> hours;
}
string getName(){
return name;
}
string getAddress(){
return address;
}
string getenrolmentDate(){
return enrolmentDate;
}
int getHours(){
return hours;
}
string getUsn(){
return usn;
}
};
}
The Second class is
#include<iostream>
using namespace std;
namespace project{
class CourseRegistration{
string usn, courseId ;
int hours, grade;
public:
CourseRegistration(project::Student obj, string courseId, int nhours, int ngrade){
usn = obj.getUsn();
this->courseId = courseId;
hours = nhours;
grade = ngrade;
}
};
}
The First class Compiles fine.But the second class gives an error.
The error is near that Student Object.
Course.cpp:10:38: error: expected ‘)’ before ‘obj’
CourseRegistration(project::Student obj, string courseId, int nhours, int ngrade){
How Do i Correct It?
I do not see any evidence you've included the definition of Student in "the second file." Your class should be delclared in a header (.h) file with the implementation in a source (.cpp) file. Your compiler is likely complaining because it doesn't know that Student is a class.
Student.h
#include<iostream>
using namespace std;
namespace project {
class Student {
private:
string name,address,enrolmentDate, usn;
int hours;
public:
Student( char*, char*, char*, char*, int );
Student();
void getData();
string getName();
string getAddress();
string getenrolmentDate();
int getHours();
string getUsn();
}
}
Student.cpp
#include "Student.h"
namespace project {
Student::Student( char* nusn, char* nname, char* naddress, char* ndate,int nhours ) {
usn = nusn;
name = nname;
address = naddress;
enrolmentDate = ndate;
hours = nhours;
}
Student() {
getData();
}
void getData() {
std::cout << "Enter Usn,Name,Address,EnrolmentDate,Hours\n";
std::cin >> usn >> name >> address >> enrolmentDate >> hours;
}
string getName() {
return name;
}
string getAddress() {
return address;
}
string getenrolmentDate() {
return enrolmentDate;
}
int getHours() {
return hours;
}
string getUsn() {
return usn;
}
}
CourseRegistration.h
#include "Student.h"
#include<iostream>
using namespace std;
namespace project{
class CourseRegistration {
private:
string usn, courseId ;
int hours, grade;
public:
CourseRegistration( Student, string, int, int );
}
}
CourseRegistration.cpp
#include<CourseRegistration.h>
namespace project {
CourseRegistration::CourseRegistration( Student obj, string courseId, int nhours, int ngrade ) {
usn = obj.getUsn();
this->courseId = courseId;
hours = nhours;
grade = ngrade;
}
}

Error: "function" is private void, error: within this context

I am fairly new to C++ and I am wanting to understand why my program is giving me this error. I constructing a program that will simulate a colony of bunnies. Being able to automatically add them, give them names, ages, etc.
These are the errors that I am getting:
main2.cpp: In function ‘int main()’:
main2.cpp:109:6: error: ‘void Bunny::printBunny()’ is private
void printBunny()
^
main2.cpp:132:26: error: within this context
colony[ i ].printBunny();
^
Here is the code that I have come up with.
enter code here
#include <iostream>
#include <string>
#include <ctime>
#include <vector>
#include <cstdlib>
using namespace std;
void setSex( void );
char getSex();
void setColor( void );
string getColor();
void setAge( void );
int getAge();
void setName( void );
string getName();
void printBunny();
static const int POSSIBLE_NAMES = 5;
static const int POSSIBLE_COLORS = 4;
class Bunny
{
char sex;
string color;
int age;
string name;
bool radioactive_mutant_vampire_bunny;
BunnyData()
{
//srand( time( 0 ) );
setSex();
setColor();
setAge();
setName();
}
void setSex()
{
int randomNumber = 1 + rand() % 2;
( randomNumber == 1 ) ? sex = 'm' : sex = 'f';
}
char getSex()
{
return sex;
}
void setColor()
{
//color = possibleColors[ 0 + rand() % POSSIBLE_COLORS ];
}
string getColor()
{
return color;
}
void setAge()
{
age = 0;
}
int getAge()
{
return age;
}
void setName()
{
//name = possibleNames[ 0 + rand() % POSSIBLE_NAMES ];
}
string getName()
{
return name;
}
void printBunny()
{
cout << "Name: " << getName() << endl;
cout << "Sex: " << getSex() << endl;
cout << "Color: " << getColor() << endl;
cout << "Age: " << getAge() << endl;
}
};
int main()
{
vector< Bunny > colony;
cout << "Welcome to Bunny Graduation!" << endl << endl;
for( int i = 0; i < 5; ++i )
{
colony.push_back( Bunny() );
}
for( int i = 0; i < 5; ++i )
{
colony[ i ].printBunny();
cout << endl;
}
return 0;
}
Everything in a class has private access unless stated otherwise For example,
class access
{
int iAmPrivate; // private. Not accessible outside of the class
public:
int getValue() //public and accessible to all
{
return iAmPrivate;
}
int iAmPublic; //also public
}
Documentation on access levels.
You need to declare them to be public, if you don't, these members are private by default, which means you cannot invoke them outside the class.
class Bunny
{public:
void printBunny() {...}
};
You really need to consider which class access modifier you should apply to the member, because normally, we don't use just one type of access modifier in OO.
You can check this site to learn more about it.
In your class:
class Bunny
{
char sex;
string color;
int age;
string name;
// Rest of class fields ...
}
All the fields are private by default. This is because you have not used the keyword public: before you declare the fields of the class Bunny. As a result, you cannot invoke/call these fields and functions outside of the class, as you have tried in:
colony[ i ].printBunny(); // you are calling a private member of class Bunny outside of the class
There are 2 ways to get around this error:
One way is that you can declare the class members as public. This will allow the functions and fields to be invoked outside of the class:
class Bunny
{
public: // declare all fields of the class as public
char sex;
string color;
int age;
string name;
// Rest of class fields ...
}
Another thing you can do is declare Bunny as a struct instead if a class. This way, all your fields sill be accessible outside the struct:
struct Bunny
{
char sex;
string color;
int age;
string name;
// Rest of class fields ...
}

Getting values from a vector of object pointers

I need to write the name, act# balance and address of the object that is stored in the vector, to a file.
I believe I have the program to push the objects into the vectors, but since they are vectors of object pointers I am having problems figure out how to call the object and print all 3 objects out.
Main.cpp
vector<Account*> accounts;
accounts.push_back(new Savings(new Person("Bilbo Baggins", "43 Bag End"), 1, 500, 0.075));
accounts.push_back(new Checking(new Person("Wizard Gandalf", "Crystal Palace"), 2, 1000.00, 2.00));
accounts.push_back(new Savings(new Person("Elf Elrond", "Rivendell"), 3, 1200, 0.050));
ofstream outFile;
outFile.open("accounts.txt");
if (outFile.fail())
{
cout << "\nYour file did not open, the program will now close!\n";
system("PAUSE");
return 0;
}
else
{
cout << "\nBINGO!!! It worked.\n\n";
system("PAUSE");
cout << "\n";
}
// New : Using a loop, send messages to each of the three Account objects to write themselves out to the file.
cout << "\nNow we are going to write the information to \"Accounts.txt\" \n\n";
system("PAUSE");
for (int i = 0; i < accounts.size(); i++) {
accounts[i]->writeAccount(outFile);
}
Account.h
#pragma once
#include <string>
#include <iostream>
#include "Person.h"
using namespace std;
// Account class - abstract/parent class
class Account
{
private:
int actNumber;
double actBallance;
Person PersonName;
public:
Account();
Account(int, double, Person*);
int getActNumber();
virtual double getActBallance();
string getName();
string getAdd();
void deposit(double);
void withdrawl(double);
virtual void writeAccount(ofstream&);
virtual void readAccount(ifstream&);
void testAccount(int i);
};
// Checking class: inherits from the Account class
class Checking : public Account
{
private:
double monthlyFee;
public:
Checking();
Checking(Person*, int, double, double);
void setMonthlyFee(double);
double getActBallance();
void writeAccount(ofstream&);
void readAccount(ifstream&);
};
// Savings class: inherits from the Account class
class Savings : public Account
{
private:
int interestRate;
public:
Savings();
Savings(Person*, int, double, double); // person, act#, Ballance, Interest Rate
void setInterestRate(double);
double getActBallance();
void writeAccount(ofstream&);
void readAccount(ifstream&);
};
Account.cpp
#include "Account.h"
#include <string>
using namespace std;
Account::Account()
{
actNumber = 0;
actBallance = 0.0;
}
Account::Account(int act, double bal, Person* name)
{
actNumber = act;
actBallance = bal;
}
int Account::getActNumber()
{
return actNumber;
}
double Account::getActBallance()
{
return actBallance;
}
string Account::getName()
{
return PersonName.getName();
}
string Account::getAdd()
{
return PersonName.getAddress();
}
void Account::deposit(double money)
{
actBallance += money;
}
void Account::withdrawl(double money)
{
actBallance -= money;
}
void Account::writeAccount(ofstream& output)
{
output << actNumber << "\n" << actBallance << "\n" << PersonName.getName() << "\n" << PersonName.getAddress() << endl;
}
void Account::readAccount(ifstream& output)
{
output >> actNumber;
output >> actBallance;
}
// Checking Account
Checking::Checking() {
monthlyFee = 0;
}
Checking::Checking(Person* per, int actNum, double bal, double interest) {
bal -= monthlyFee;
Account:Account(actNum, bal, per);
}
void Checking::setMonthlyFee(double fee) {
monthlyFee = fee;
}
double Checking::getActBallance() {
double ballance = Account::getActBallance();
return ballance = monthlyFee;
}
void Checking::readAccount(ifstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance() - monthlyFee;
output >> actNumber;
output >> actBallance;
}
void Checking::writeAccount(ofstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance();
output << actNumber << "\n" << actBallance << endl;
}
// Savings Account
Savings::Savings() {
interestRate = 0;
}
// Savings(Person, int, double, double) // person, act#, Ballance, Interest Rate
Savings::Savings(Person* per, int actNum, double bal, double interest) {
bal += (bal * interest);
Account:Account(actNum, bal, per);
}
void Savings::setInterestRate(double rate) {
interestRate = rate;
}
double Savings::getActBallance() {
double ballance = Account::getActBallance();
return ballance + (ballance * interestRate);
}
void Savings::readAccount(ifstream& output) {
double actBallance = Account::getActBallance();
int actNumber = Account::getActNumber();
actBallance += (actBallance * interestRate);
output >> actNumber;
output >> actBallance;
}
void Savings::writeAccount(ofstream& output) {
int actNumber = Account::getActNumber();
int actBallance = Account::getActBallance();
output << actNumber << "\n" << actBallance << endl;
}
I realize I am so far off... but I have been at this for HOURS and I can not figure out for the life of me, but to take the vector of object pointers and output the objects values.
Person.h
#pragma once
#include <string>
#include <fstream>
using namespace std;
class Person
{
private:
string name;
string address;
public:
Person();
Person(string a, string b);
string getName();
string getAddress();
void writePerson(ofstream&);
void readPerson(ifstream&);
};
Person.cpp
#include "Person.h"
#include <string>
using namespace std;
Person::Person()
{
name = "NAME";
address = "123 STREET";
}
Person::Person(string a, string b)
{
name = a;
address = b;
}
string Person::getName()
{
return name;
}
string Person::getAddress()
{
return address;
}
void Person::writePerson(ofstream& output)
{
output << name << " " << address << endl;
}
void Person::readPerson(ifstream& output)
{
output >> name;
output >> address;
Person(name, address);
}
Read again your course books on constructors: there are severe issues in all of your constructors. As a result, you don't initialize the object member variables, and you effectively end up printing lots of zeros and empty strings...
Firstly, for your base-class, you must initialize the person name. You should have written:
Account::Account(int act, double bal, Person* name)
: actNumber(act)
, actBallance(bal)
, PersonName(name)
{}
Secondly, for your derived classes, the initialisation of the base-class must be done in the initializer-list, not in the body of the ctor. Here is for exemple the correct definition for the Checking's ctor:
Checking::Checking(Person* per, int actNum, double bal, double interest)
: Account(actNum, bal, per)
, monthlyFee(-bal)
{}
Thirdly, be careful to initialize the member variables with the arguments of the ctor. You sometimes do the opposite and assign the ctor arguments with the (uninitialized) member variables.
BTW, Account is a base-class for a polymorphic hierarchy: thus, the Account destructor must be declared virtual.

Trying to print information stored in an array of type object in C++

I'm just starting to learn object oriented programming in C++ and am having issues figuring out how to print an object that is stored inside an array. From what I know, I want to just try to try and go through the array and print out each employee object, how because objects are different than variables like int and double I'm sure it's causing a problem. Is my logic wrong, or is it just syntax? Here is my code:
Header:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
using namespace std;
class Employee
{
private:
string name;
string idNumber;
string department;
string position;
int yearsWorked;
public:
Employee();
Employee(string, string);
Employee(string, string, string, string, int);
void setName(string);
void setIdNumber(string);
void setDepartment(string);
void setPosition(string);
bool setYearsWorked(int);
string getName()const;
string getIdNumber()const;
string getDepartment()const;
string getPosition()const;
int getYearsWorked()const;
};
#endif
Implementation:
#include "Employee.h"
using namespace std;
Employee::Employee()
{
string name = "";
string idNumber = "";
string department = "";
string position = "";
int yearsWorked = 0;
}
Employee::Employee(string nm, string id)
{
string name = nm;
string idNumber = id;
string department = "";
string position = "";
int yearsWorked = 0;
}
Employee::Employee(string nm, string id, string dpt, string pos, int years)
{
string name = nm;
string idNumber = id;
string department = dpt;
string position = pos;
int yearsWorked = years;
}
void Employee::setName(string nm)
{
name = nm;
}
void Employee::setIdNumber(string id)
{
idNumber = id;
}
void Employee::setDepartment(string dpt)
{
department = dpt;
}
void Employee::setPosition(string pos)
{
position = pos;
}
bool Employee::setYearsWorked(int years)
{
if (years >= 0)
{
yearsWorked = years;
return true;
}
else
return false;
}
string Employee::getName()const
{
return name;
}
string Employee::getIdNumber()const
{
return idNumber;
}
string Employee::getDepartment()const
{
return department;
}
string Employee::getPosition()const
{
return position;
}
int Employee::getYearsWorked()const
{
return yearsWorked;
}
Main:
#include <iostream>
#include <iomanip>
#include "Employee.h"
using namespace std;
const int SIZE = 3;
int main()
{
Employee emp1("Jenny Jacobs", "JJ8990", "Accounting", "President", 15);
Employee emp2("Myron Smith", "MS7571", "IT", "Programmer", 5);
Employee emp3("Chris Raines", "CR6873", "Manufacturing", "Engineer", 30);
Employee employees[SIZE] = {emp1, emp2, emp3};
for (int i = 0; i < SIZE; i++)
{
cout << employees[i] << endl;
}
system("PAUSE");
return 0;
}
Add this:
std::ostream& operator<<( std::ostream& stream, Employee const& emp )
{
return (stream << emp.getName());
}
Modify as needed.
General comments:
Do not place using namespace std; in the global namespace in a header. Keep in mind that the standard library defines very common names like distance. Which can easily lead to name collisions.
Reserve ALL UPPERCASE names for macros, to reduce the chance of name collisions and inadvertent text substitution.
Preferentially pass potentially "large" objects, such as std::string, by reference, e.g. formal argument type std::string const&, in order to avoid excessive copying. There are some exceptions to this rule when one aims for perfect code, e.g. for C++11 move semantics, but it's a good general rule.
employees[i] is of type Employee. So either you have to print like
cout<<employees[i].getName(); // so on
Or you have to overload << operator for Employee type:
ostream& operator<<(ostream& stream, Employee const& emp );
Firstly. in my machine it compiles fine
Secondly, you are doing:
string name = nm;
So name is a automatic variable, Not the member of your class. You should do like:
name = nm; // if you delete int name; line
Or,
this->name = nm;
Some changes of your code:
Employee::Employee()
: yearsWorked( 0 )
{
}
Employee::Employee(string nm, string id)
: name( nm ), idNumber( id ), yearsWorked( 0 )
{
}
Employee::Employee(string nm, string id)
: name( nm ), idNumber( id ), department( dpt ), position( pos ), yearsWorked( years ),
{
}
std::ostream & operator <<( std::ostream &os, const Employee &emp )
{
return ( os << "ID: " << emp.idNumber << ", name: " << emp.name
<< ", department: " << emp.department << ", position: " << emp.position
<< ", years worked: " << emp.yearsWorked );
}