I'm currently working on an assignment to expand on a program we previously made, involving the use of header files, and parent classes. In the original, I have 2 header files. Person.h, and OCCCDate.h. In the new one, I am creating one called OCCCPerson.h. It's an incredibly simple class that basically just uses Person, just with 1 added variable.
My problem is, I cant figure out how to use the parent constructor properly.
Here is the Person.h file.
#ifndef PERSON_H
#define PERSON_H
#include <string>
#include "OCCCDate.h"
using namespace std;
class Person{
private:
string firstName;
string lastName;
OCCCDate dob;
public:
Person();
Person(string, string);
Person(string, string, OCCCDate);
string getFirstName();
string getLastName();
void setFirstName(string);
void setLastName(string);
int getAgeInYears();
bool equals(Person);
string toString();
};
#endif
And here is my OCCCPerson.h file
#ifndef OCCCPERSON_H
#define OCCCPERSON_H
#include <string>
#include "OCCCDate.h"
#include "Perosn.h"
using namespace std;
class OCCCPerson : Person{
protected:
string studentID;
public:
OCCCPerson(string firstName, string lastName, OCCCDate dob, string studentID);
OCCCPerson(Person p, string studentID);
string getStudentID();
bool equals(OCCCPerson p);
string toString();
};
#endif;
I cant seem to call on the parents constructor to get things like the firstname, lastname, and dob(date of birth). From my handout, it says the parent constructor has to be initialized with, : Person(parameters), where parameters are things in the parent class. However, I have no idea where to put that. Sorry for writing so much. I just couldn't figure out how to shrink that down.
Oh, and here is OCCCDate.h just in case
#ifndef OCCCDATE_H
#define OCCCDATE_H
#include<string>
using namespace std;
class OCCCDate{
private:
bool OCCCDate_US;
bool OCCCDate_EURO;
int dayOfMonth, monthOfYear, year;
bool dateFormat;
public:
OCCCDate();
OCCCDate(int dayOfMonth, int monthOfYear, int year);
int getDayOfMonth();
int getMonth();
string getNameOfMonth();
int getYear();
string getDate();
int getDifference(OCCCDate d1, OCCCDate d2);
int getDifference(OCCCDate d1);
void setDateFormat(bool);
bool equals(OCCCDate d);
string toString();
};
#endif
And here is my OCCCDate.cpp file
#include<iostream>
#include<ctime>
#include "OCCCPerson.h"
using namespace std;
OCCCPerson::OCCCPerson(string firstName, string lastName, OCCCDate dob, string studentID):Person(firstName, lastName, dob){
string firstName = Person::getFirstName();
string lastName = Person::getLastName();
OCCCDate dob = dob;
this->studentID = studentID;
}
OCCCPerson::OCCCPerson(Person p, string studentID){
Person p = p;
this->studentID = studentID;
}
What you need is member initializer lists.
From cppreference:
In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual base subobjects and non-static data members.
A simple example:
class MyClass : BaseClass
{
public:
MyClass(int arg) : BaseClass(arg) {
//Rest of code
}
}
In your case, you can do:
OCCCPerson(string firstName, string lastName, OCCCDate dob, string studentID) :
Person(firstName, lastName, dob) {
this.studentID = studentID;
}
In OCCCPerson.cpp,
OCCCPerson(string firstName, string lastName, OCCCDate dob, string
studentID) : Person(firstName, lastName, dob)
{
//more stuff
}
You basically have to use an initializer list.
Read more here: What are the rules for calling the superclass constructor?
What this does is it calls the parent constructor Person(string, string, OCCCDate) and basically performs this->firstName = firstName. Similarly for lastName and dob. But not studentID because the Person(string, string, OCCCDate) constructor doesn't provide initialization for studentID.
Related
I have created a class name Employee and inside that I have declared a function and two variable(name ,age) . After creating a variable x I am not getting the name insted getting empty name and age =0
CODE:
#include<iostream>
using namespace std;
class Employee{
public:
string name;
int age;
void print(){
cout<<"Name:"<<name<<endl;
cout<<"Age:"<<age<<endl;
}
Employee(string name,int age){
name = name;
age=age;
}
};
int main(){
Employee x=Employee("chang",33);
x.print();
return 0;
}
Expected:
name:Chang
age :33
OutPut:
name:
age :0
Can Someone tell me what is the reason behind it.
Employee(string name, int age) {
name = name;
age = age;
}
you are not modifying the class members, but the parameters instead.
You have three ways to solve this problem:
use this-> to precisely target the right variables.
Employee(string name, int age) {
this->name = name;
this->age = age;
}
use an initialisation list:
Employee(string name, int age) : name(name), age(age) {
}
don't use any constructor, but use brace initialization instead:
int main() {
Employee x = Employee{ "chang", 33 };
x.print();
}
I would personally use option three with the braces, as it's the most efficient to write.
read here why you shouldn't be using namespace std;
I am trying to use constructor initializer for name and time but the visual studio is giving me errors, I do not see any issues with it, it seems fine to me, I tried to see the problem, I tried other things as well, Please Help. Thanks you in advance.
Any help really appreciated, I added all the header file and implementation of Entry class, I know it seems, I added so you can see it.
// Entry.h
#pragma once
#include <iostream>
#include <string>
#include "RelationType.h"
using namespace std;
class Name
{
public:
Name();
Name(string firstName, string middleName, string lastName);
string GetFristName() const;
string GetLastName() const;
string GetMiddleName() const;
char GetMiddleInitial() const;
RelationType ComparedTo(Name otherName) const;
private:
string first;
string last;
string middle;
};
//Entry.cpp
#include "Entry.h"
#include<iostream>
#include <string>
using namespace std;
Entry::Entry() {}
Entry::Entry(string firstName, string middleName, string lastName,
int initHours, int initMinutes, int initSeconds)
: name{ (firstName, middleName, lastName) , //name is where its mad at
time(initHours, initMinutes, initSeconds) } {}
string Entry::GetNameStr () const
{
return (name.GetFirstName() + ' ' + name.GetLastName());
}
string Entry::GetTimeStr () const
{
return (name.FirstName() + ' ' + name.LastName());
}
// Name.h
#pragma once
#include <iostream>
#include <string>
#include "RelationType.h"
using namespace std;
class Name
{
public:
Name();
Name(string firstName, string middleName, string lastName);
string GetFristName() const;
string GetLastName() const;
string GetMiddleName() const;
char GetMiddleInitial() const;
RelationType ComparedTo(Name otherName) const;
private:
string first;
string last;
string middle;
};
// RealtionType.h
#pragma once
#ifndef RELATION
#define RELATION
enum RelationType { BEFORE, SAME, AFTER };
#endif
// TimeOfDay.h
#pragma once
class TimeOfDay
{
public:
//Intentionally missed const, see what happened without const
TimeOfDay(); // zero timepfday object
TimeOfDay(int hours, int minutes, int seconds); //takes 3 parameters
TimeOfDay Increment() const; //increment by 1 sec
void Write() const; //write the timeofday obj to print
bool Equal(TimeOfDay otherTime) const; //true if timeofday obj equals othertime
bool LessThan(TimeOfDay otherTime) const; //const, true if the timeofday obj is
//before itherTime
private:
int hours;
int minutes;
int seconds;
};
Your Entry class constructor code should be something like below
Entry::Entry(string firstName, string middleName, string lastName,
int initHours, int initMinutes, int initSeconds)
: name(firstName, middleName, lastName)
, time(initHours, initMinutes, initSeconds) {}
I am new to this. Basically I just learnt how to use class in C++. When I try to print out, the values just seem to be 0. Can anyone help me out? Its supposed to print out:
Susan Myers 47899 Accounting Vice President
Mark Jones 39119 IT Position
Joy Rogers 81774 Manufacturing Engineer
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee
{
private:
string name;
int idNumber;
string department;
string position;
public:
Employee()
{
name=" ";
idNumber=0;
department=" ";
position=" ";
}
Employee(string, int, string, string)
{
int id;
string n,d,p;
name=n;
idNumber=id;
department=d;
position=p;
}
Employee(string, int)
{
string n;
int id;
name=n;
idNumber=id;
}
void setName(string)
{
string n;
name=n;
}
void setId(int)
{
int id;
idNumber=id;
}
void setDepartment(string)
{
string d;
department=d;
}
void setPosition(string)
{
string p;
position=p;
}
string getName() const
{
return name;
}
int getId() const
{
return idNumber;
}
string getDepartment() const
{
return department;
}
string getPosition() const
{
return position;
}
};
int main()
{
Employee e1;
Employee e2;
Employee e3;
e1.setName("Susan Meyers");
e2.setName("Mark Jones");
e3.setName("Joy Rogers");
e1.setId(47899);
e2.setId(39119);
e3.setId(81744);
e1.setDepartment("Accounting");
e2.setDepartment("IT");
e3.setDepartment("Manufacturing");
e1.setPosition("Vice President");
e2.setPosition("Programmer");
e3.setPosition("Engineer");
cout<<"---------------------------------------"<<endl;
cout<<"Name"<<setw(6)<<"ID Number"<<setw(10)<<"Department"<<setw(12)<<"Position"<<endl;
cout<<e1.getName()<<setw(6)<<e1.getId()<<setw(10)<<e1.getDepartment()<<setw(12)<<e1.getDepartment()<<endl;
cout<<e2.getName()<<setw(6)<<e2.getId()<<setw(10)<<e2.getDepartment()<<setw(12)<<e2.getDepartment()<<endl;
cout<<e3.getName()<<setw(6)<<e3.getId()<<setw(10)<<e3.getDepartment()<<setw(12)<<e3.getDepartment()<<endl;
return 0;
}
This is what you get when you rely on guesswork rather than properly reading an introductory textbook on C++
A constructor of the Employee class which (apart from a blank line that I've removed) you define as
Employee(string, int, string, string)
{
int id;
string n,d,p;
name=n;
idNumber=id;
department=d;
position=p;
}
has the following effects.
The four arguments passed by the caller are ignored, since they are not named.
Four default-initialised variables (id, n, d, and p) are defined local to the constructor body. id will be uninitialised. The others, since they are std::string, are default-initialised (to an empty string)
The next four statements copy those variables into class members. The result is that initialising idNumber has undefined behaviour (since id is uninitialised) and the three strings are initialised to empty strings.
To get the effect that (I assume) you intend, change this to;
Employee(std::string n, int id, std::string d, std::string p)
{
name=n;
idNumber=id;
department=d;
position=p;
}
Note that I'm calling string by its full name std::string. That allows removing the using namespace std which (among other things) is BAD practice in header files.
Even better, change this to
Employee(const std::string &n, int id, const std::string &d, const std::string &p) :
name(n), idNumber(id), department(d), position(p)
{
}
which passes the strings by const reference (avoids additional copies of std::strings) and uses an initialiser list instead of assigning to members in the constructor.
Similar comments apply to ALL of the member functions of Employee, except that only constructors can have initialiser lists.
Errors made
Presentation
Your code is extremely cluttered, and has much irrelevant stuff.
Syntax
void setPosition(string){
Here your function has no argument! What is string?
Code
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee{
public:
string name;
int idNumber;
string department;
string position;
void setName(string n){
name=n;
}
void setId(int k){
int id;
idNumber=id;
}
void setDepartment(string d){
department=d;
}
void setPosition(string p){
position=p;
}
string getName(){
return name;
}
int getId(){
return idNumber;
}
string getDepartment(){
return department;
}
string getPosition(){
return position;
}
};
int main(){
Employee e1;
Employee e2;
Employee e3;
e1.setName("Susan Meyers");
e2.setName("Mark Jones");
e3.setName("Joy Rogers");
e1.setId(47899);
e2.setId(39119);
e3.setId(81744);
e1.setDepartment("Accounting");
e2.setDepartment("IT");
e3.setDepartment("Manufacturing");
e1.setPosition("Vice President");
e2.setPosition("Programmer");
e3.setPosition("Engineer");
cout<<"---------------------------------------"<<endl;
cout<<"Name"<<" "<<"ID Number"<<" "<<"Department"<<" "<<"Position"<<endl;
cout<<e1.getName()<<" "<<e1.getId()<<" "<<e1.getDepartment()<<" "<<e1.getPosition()<<endl;
cout<<e2.getName()<<" "<<e2.getId()<<" "<<e2.getDepartment()<<" "<<e2.getPosition()<<endl;
cout<<e3.getName()<<" "<<e3.getId()<<" "<<e3.getDepartment()<<" "<<e3.getPosition()<<endl;
}
Output
---------------------------------------
Name ID Number Department Position
Susan Meyers 32767 Accounting Vice President
Mark Jones 32767 IT Programmer
Joy Rogers 32767 Manufacturing Engineer
Explanation
I have shortened your code by 50%(shows how much redundant stuff you had), and here is a working code.
void setDepartment(string d){
department=d;
}
Here, string d is defined IN the function as an argument. Note that your code also cout<< department twice, and I have corrected that for you in my above code.
Hope this helps.
when I have the following member in a class
employee headOfDepartment;
what's wrong these setters and getters?
void department::setHeadOfDepartment( employee depEmployee)
{
headOfDepartment=depEmployee;
}
employee department::getHeadOfDepartment()
{
return headOfDepartment;
}
I've been trying forever to define setters & getters with composition and it keeps getting me this error: "field ‘headOfDepartment’ has incomplete type"
ok Those are the header files:
#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_
using namespace std;
#include <iostream>
#include <vector>
#include "department.h"
#include "project.h"
class department;
class project;
//#include <vector>
employee.h
class employee
{
string Name; //text with spaces
string National_ID; //unique value (text) for each employee
static double Salary; // value of 1500 pounds
char Gender; //character holds f or m
int Available_vacations; //initially starts with 15 days
static double Deduction_per_day; // value of 85.5 pounds
int Available_permission_hours; //initially starts with 20 hours
static double Deduction_per_hour; // value of 15.5 pounds
double Actual_salary; // value with actual salary after deductions
int Vacations; // vacations employee took
int Permessions; // permession hours employee took
int empSerialNum; // object order in vector
department* myDepartment;
vector < project > empProjects;
public:
employee (); // default constructor
employee (string myName, string myNationalID, char myGender,int mySerialNum); // Parameterized constructor
~employee(); // Destractor
//Setters
void setName(string myName);
void setNationalID (string myNationalID);
void setGender (char myGander);
void setAvailableVacation(int myAvVac);
void setAvailablepermissionhours (int myAvPerHours);
void setActualSalary (double actualSalary);
void setVacations(int myVacations);
void setPermessions(int myPermessions);
void setempSerialNum(int mySerialNum);
void setDepartment(department*);
void addProject(project);
//Getters
string getName();
string getNationalID ();
char getGender ();
int getAvailableVacation();
int getAvailablepermissionhours ();
double getActualSalary ();
int getVacations ();
int getPermessions ();
int getempSerialNum();
department* getDepartment();
project* getProjects();
void view (); // View to view Name, ID and actual salary
void View_Detailed (); //call previous function and also shows other details (vacations - permissions - detailed deductions - ... )
void Free_All(); //return all values to default
double Take_vacation(); //this function takes number of days employee need to take as vacation, available vacations reduced by number of days given, if available vacations became 0 salary is deduced by deduction per day set
double Take_permession(); //this function takes hours that employee asked to take, reduce available permission hour by hours given, if available permission become 0 hour salary is reduced by deduction per ho
double Calculate_Actual_Salary();// calculates salary after deductions and returns it
};
#endif
department.h
#ifndef DEPARTMENT_H_
#define DEPARTMENT_H_
using namespace std;
#include <string.h>
#include "employee.h"
#include "project.h"
#include <vector>
class project;
class employee;
class department{
private:
string name;
string ID;
employee headOfDepartment;
vector <project> depprojects; //projects managed by the department
public:
//constructors
department();
department(string, string);
//Setters
void setName(string);
void setID(string);
void setHeadOfDepartment( employee /*const&*/ depEmployee);
void addProject(project);
//Getters
string getName();
string getID();
employee getHeadOfDepartment() /*const*/;
// project getProjects();
};
#endif
project.h
#ifndef PROJECT_H_
#define PROJECT_H_
#include <string.h>
#include "department.h"
#include "project.h"
class department;
class project{
string name;
department* location;
public:
//constructors
project();
project(string proName, department* proDepartment);
//Setters
void setName(string proName);
void setLocation(department* proDepartment);
//Getters
string getName();
department* getLocation();
};
#endif
You need to the include the header file where employee is declared in your header and source files for department
Class employee shall be defined before using it as a type name of an object. Also I advice to add qualifier const for the getter
You are not including the header that defines employee in your department class header, but you have a non-reference non-pointer declaration of type employee in your header.
I'm trying to create a member function that allows an user to set member array variables.
I've been looking everywhere but I can't find the problem in my code,
#include <string>
#include <iostream>
using namespace std;
class Employee
{
protected:
string name;
char ssn[11];
char id[5];
char hired[8];
public:
Employee(char ssn, char id, char hired); //Constructor
Employee(string name);
~Employee(); //Destructor
void setName(string n) { n = name; }
void setSSN(char i) { ssn = i; }
};
int main()
{
return 0;
}
Let's have a look at your setSSN function:
void setSSN(char i) { ssn = i; }
SNN, which most likely means social security number, doesn't consist of just one digit but 11, right? Then why would setSSN take as input only one character (digit) by (char i)? So setSSN function should rather take a string of characters containing SSN of the employee and that string should be of the same flavor as the ssn member variable of your Employee class in order to let you assign one string variable by another in the body of setSSN function. If you are already familiar with the string class of the C++ standard library, you should probably use that class for all your string storage and manipulation.